Search code examples
cstringmemory-leaksrealloc

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.


Solution

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