Search code examples
cmemory-leaksstrdup

memory leak with repeated strdup's


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;
   }

Solution

  • As discussed in comments, the leak is fixed by

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

    When array is no longer needed