[cs631apue] Using malloc to dynamically create an array of pointers to strings in C
mseaton
mseaton at stevens.edu
Sat Sep 24 21:57:40 EDT 2016
Hello,
Like argv**, when dynamically creating an array of pointers to string,
where each pointer in the array points to a C string of variable length,
you have to use malloc twice, one for the array of pointers and one for
each string that each array index will point to. Is is absolutely
necessary to use free() twice as well?
for example:
char **filenames;
filenames = malloc(sizeof(char*) * numfiles);
filenames[i] = malloc( (strlen(direntptr->d_name) + 1) * sizeof(char));
Given the two malloc calls above, would I need these two calls to free
or is the second call sufficient?
for(i = 0; i < numfiles; i++)
free(filenames[i]);
free(filenames);
I am asking this because I am getting a core dump error involving
free(). This error is not always occurring. It's happening on and off.
Marlon
More information about the cs631apue
mailing list