简体   繁体   中英

Memory leak with string arrays in c

char **add_string(char **existing, const char *string){
  size_t size = 0;
  while (NULL != existing[size]) 
    {
      ++size; 
    }
  char **arr = realloc(existing, (size + 2) * sizeof *arr);
  arr[size] = malloc(strlen(string) + 1);
  strcpy(arr[size], string);  
  arr[size+1] = '\0';
  return arr;
}

void free_strings(char **strings)
{
  size_t size = 0;
  while (NULL != strings[size]) 
  {
    free(strings[size]);
    ++size;
  }
}

I am having a memory leak at line

char **arr = realloc(existing, (size + 2) * sizeof *arr);

I thought existing memory was suppose to be free'd when using realloc? How do I fix this memory leak?

edit: added my free_string function and the main I am using to run the program.

You did not append the array pointed to by the pointer existing with null pointer. Thus in this loop

while (NULL != existing[size]) { ++size; }

the function has undefined behavior.

It seems you mean the following

char ** add_string( char **existing, const char *string )
{
    size_t size = 0;

    while ( NULL != existing[size] ) ++size; 

    char **arr = realloc( existing, ( size + 2 ) * sizeof *arr );

    if ( arr != NULL )
    {
        arr[size] = malloc( strlen( string ) + 1 );
        strcpy( arr[size], string );  
        arr[size+1] = NULL;
    }

    return arr;
}

Also the function free_strings is incorrect. It should look like

void free_strings( char **strings )
{
    size_t size` = 0;

    do
    {
        free( strings[size] );
    } while ( strings[size++] != NULL );

    free( strings );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM