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

Keyur Ved kved at stevens.edu
Wed Oct 3 10:51:39 EDT 2018


Hi Marlon,

strcpy will return the number of bytes copied, make sure that it is the
correct number with each call. Also it's safer to use strncpy since you
know the number of bytes you want to copy each time.

On Wed, Oct 3, 2018, 6:57 AM Marlon Seaton <mseaton at stevens.edu> wrote:

> Good morning,
>
> I am have the following memory error: Error in `./ls': corrupted size vs.
> prev_size: Can't seem to figure out why, but I believe it may have to do
> with how I am trying to allocate an array of pointers to strings. I guess
> my question is could the following code snippet potentially cause the
> problem that I am having?
>
>
> Here's the code below:
>
> pfilenames = malloc((numfiles + 1) * sizeof(char*));
>    if(pfilenames == NULL)
>    {
>        perror("malloc failed\n");
>        exit(EXIT_FAILURE);
>    }
>
> pfilenames[i] = malloc( (strlen(direntptr->d_name) + 1) * sizeof(char));
>          if(pfilenames[i] == NULL)
>          {
>               perror("malloc failed\n");
>                exit(EXIT_FAILURE);
>          }
>
>          strcpy(pfilenames[i], direntptr->d_name);
>          i++;
>  numfiles is the number of files in the directory. I keep a running total
> of this as I am reading the files in the directory.
>
>
> Thank you.
>
> Marlon
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.stevens.edu/pipermail/cs631apue/attachments/20181003/835ace4a/attachment.html>


More information about the cs631apue mailing list