Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

*Program is in C* (a) Draw a picture of the memory and pointers created by the a

ID: 3883239 • Letter: #

Question

*Program is in C*

(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.

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-o; i

Explanation / Answer

Dear Student,

here is the complete c program which free the memory allocated by the pointer.

----------------------------------------------------------------------------------------------------------------------------------------

Note: Please note that the below program has been tested on ubuntu 16.04 system and compiled under gcc compiler. This code will also work on other IDE's.

------------------------------------------------------------------------------------------------------------------------------------------

Program:

-------------------------------------------------------------------------------------------------------------------------------------

#include<stdio.h>

#include<stdlib.h>

int main()

{

char **ppArrayOfPointers;

ppArrayOfPointers = (char**)malloc(5*sizeof(char*));

if(ppArrayOfPointers == NULL)

{

perror("malloc error");

exit(1);

}

int i;

for(i=0;i<5;i++)

{

ppArrayOfPointers[i] = (char*)malloc(3*sizeof(char));

}

if(ppArrayOfPointers[i] == NULL)

{

perror("malloc error");

exit(1);

}

//this statement will free the memory allocated by the pointers

free(ppArrayOfPointers);

return 0;

}


-----------------------------------------------------------------------------------------------------------------------------------------

Note: The program will successfully compiled without throwing any error and warning message, it means the memory has been successfully allocated for the pointer and and finally memory has been freed.

------------------------------------------------------------------------------------------------------------------------------------------