[cs631apue] memory leak error I can't seem to find

Jan Schaumann jschauma at stevens.edu
Wed Oct 3 22:26:49 EDT 2018

Marlon Seaton <mseaton at stevens.edu> wrote:
> could the following code snippet potentially cause the problem that I
> am having?

Hard to say, since your code snippet is incomplete and we don't know
what you're doing around this; presumably it's in a loop, and it's quite
possible that you're moving beyond the initial size of 'pfilenames'.

The general idea of doing

char **names;
names = malloc(num * sizeof(char*));
for (i =0; i<num; i++) {
	names[i] = malloc(len * sizeof(char));
	strncpy(names[i], whatever, len);

is ok, so I'm guessing a boundaries issue on 'i'.  gdb(1) to the rescue!

You may also wish to instead let strdup(3) do the malloc(3) for you:

names[i] = strdup(whatever);

(Remember to add error checking to all of the above.)

Also, as stressed in class, I'd recommend against using opendir(2) /
readdir(2) and instead using fts(3) for filesystem hierarchy


More information about the cs631apue mailing list