3

I am creating an array of filenames obtained from a linux_dirent structure (d). At each iteration of a loop a filename is obtained using

d_entry = strdup(d->d_name);

and a pointer to this is added to the array:

srcList[aSz] = d_entry;

As the array of pointers needs to have valid memory to point to I can't do this:

d_entry = strdup(d->d_name);
srcList[aSz] = d_entry;
free(d_entry);

Using free(d_entry) after the last use of the array only frees the memory allocated by strdup/malloc for the last instance of d_entry.

Valgrind confirms the memory leak.

Is there a way of dealing with this or should I look at using say memcpy to move the filenames to a separate buffer before creating the pointers in the array.

The core loop:

   for (bpos = 0; bpos < nread;) {
       d = (struct linux_dirent *) (buf + bpos);
       d_type = *(buf + bpos + d->d_reclen - 1);
       if( d->d_ino != 0 && d_type == DT_REG || d_type == DT_UNKNOWN ) {

           /* get directory entry */
            d_entry = strdup(d->d_name); // << repeat allocations here

           /* save pointer to filename in array 'srcList' */
                srcList[aSz] = d_entry;
                aSz++;
       }
       if ( aSz == DAY_COUNT +1 ) break;
       bpos += d->d_reclen;
   }
11
  • 1
    Make sure you free() the entries in srcList[] when you no longer need them?
    – EOF
    Feb 23, 2016 at 0:11
  • 1
    Why don't you just iterate your array later and free everything?
    – nneonneo
    Feb 23, 2016 at 0:14
  • 1
    You need to call free once for each call to strdup, sooner or later
    – M.M
    Feb 23, 2016 at 0:18
  • 3
    @anita2R the pointers are in your srcList....
    – nneonneo
    Feb 23, 2016 at 0:20
  • 1
    So? NULL the little b...blighters. Feb 23, 2016 at 0:25

1 Answer 1

1

As discussed in comments, the leak is fixed by

for ( i=0; i< size;i++)
   free( srcList[i] );

When array is no longer needed

2
  • That works, but as some elements in the array were not populated I used if(srcList[n]) free(srcList[n]); . The array was initialized to nulls and so only populated elements were used for free.
    – anita2R
    Feb 23, 2016 at 14:34
  • @anita2R I'm four years late, but free() is safe to call on NULL if implementation follows ISO en.cppreference.com/w/c/memory/free Nov 17, 2021 at 0:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.