Write the types of memory errors, the line number where each occurs and where ea
ID: 3691746 • Letter: W
Question
Write the types of memory errors, the line number where each occurs and where each error is caused:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i, j, k, n;
int w = 3;
int h = 3;
int d = 3;
int *buffer = (int *)malloc(w*h*d*sizeof(int));
int **buffer2 = (int **)malloc(w*h*d*sizeof(int *));
int count = 0;
for(i = 0; i < w; i++){
for(j = 0; i < h; j++){
for(k = 0; k < d; k++){
buffer[i*h*d + j*d + k] = count;
count++;
}
}
}
for(n = 0; n < w*h*d; n++){
buffer2[n] = &buffer[n];
}
free(buffer);
for(n = 0; n < w*h*d; n++){
printf("%d ", *buffer2[n]);
}
free(buffer2);
}
Memory errors:
array bounds read
array bounds write
free memory read
free memory write
freeing unallocated memory
freeing non-heap memory
NULL pointer read
NULL pointer write
uninitialized memory read
Explanation / Answer
int *buffer = (int *)malloc(w*h*d*sizeof(int));
/* NULL pointer read and NULL pointer write occurs here */
int **buffer2 = (int **)malloc(w*h*d*sizeof(int *));
int count = 0;
for(i = 0; i < w; i++){
for(j = 0; i < h; j++){
for(k = 0; k < d; k++){
/* array bounds read and array bounds write occurs here */
buffer[i*h*d + j*d + k] = count;
count++;
}
}
}
for(n = 0; n < w*h*d; n++){
/* uninitialized memory read occurs here */
buffer2[n] = &buffer[n];
}
free(buffer);
for(n = 0; n < w*h*d; n++){
printf("%d ", *buffer2[n]);
}
/* freeing unallocated memory and freeing non-heap memory */
/* free memory read and free memory write error occurs here*/
free(buffer2);
/*the cause for these errors is buffer array is not declared any where */
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.