Please code in C 6. Using free() Consider the following code which creates a 2D
ID: 3884451 • Letter: P
Question
Please code in C
6. Using free()
Consider the following code which creates a 2D array. It first creates an “outer array” of character pointers, and then for each pointer in the outer array it creates an “inner array” of characters.
//The ** implies that the variable is a pointer to a pointer. //That is, this variable stores the address of a character pointer.
char **ppArrayOfPointers;
ppArrayOfPointers = (char **)malloc(5*sizeof(char *));
//If malloc fails (e.g. there is not enough memory) then it returns NULL.
//If so we print an error message and quit
if(ppArrayOfPointers == NULL) { perror("malloc error"); exit(1); }
int i; for(i=0; i<5; i++) { ppArrayOfPointers[i] = (char *)malloc(3*sizeof(char)); //If malloc fails then we quit. if(ppArrayOfPointers[i] == NULL) { perror("malloc error"); exit(1); } }
(a) Draw a picture of the memory and pointers created by the above code.
(b) Write code to free all of memory allocated in the above code without causing any memory leaks.
Explanation / Answer
ppArrayOfPointers[5]
ppArrayOfPointers[0] points to 3 characters
base address = 1000
ppArrayOfPointers[1] points to 3 characters
base address = 1001
ppArrayOfPointers[2] points to 3 characters
base address = 1002
ppArrayOfPointers[3] points to 3 characters
base address = 1003
ppArrayOfPointers[4] points to 3 characters
base address = 1004
b)
int i;
for(i=0;i<5;i++)
free(ppArrayOfPointers[i]);
ppArrayOfPointers[0]= 1000 ppArrayOfPointers[1] =1001 ppArrayOfPointers[2] =1002 ppArrayOfPointers[4] =1003 ppArrayOfPointers[5] =1004