[cs631apue] Using malloc to dynamically create an array of pointers to strings in C

Patrick Murray pmurray1 at stevens.edu
Sun Sep 25 19:12:34 EDT 2016


Hi Marlon,

Yes it would be necessary to free each char* entry within the char** array
prior to freeing the array itself. Please note that this step is only
required
if the contents of the array are malloc'd. Valgrind and GDB are very useful
for
debugging memory errors and leaks.

[0] http://valgrind.org/
[1] https://www.gnu.org/software/gdb/


On Sat, Sep 24, 2016 at 9:57 PM, mseaton <mseaton at stevens.edu> wrote:

> 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
> _______________________________________________
> cs631apue mailing list
> cs631apue at lists.stevens.edu
> https://lists.stevens.edu/mailman/listinfo/cs631apue
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.stevens.edu/pipermail/cs631apue/attachments/20160925/4ed61c2e/attachment.html>


More information about the cs631apue mailing list