简体   繁体   English

c中字符串数组的内存泄漏

[英]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?我认为在使用 realloc 时应该释放现有内存? How do I fix this memory leak?如何修复此内存泄漏?

edit: added my free_string function and the main I am using to run the program.编辑:添加了我的 free_string 函数和我用来运行程序的主函数。

You did not append the array pointed to by the pointer existing with null pointer.您没有附加由空指针existing的指针指向的数组。 Thus in this loop因此在这个循环中

while (NULL != existing[size]) { ++size; 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.函数free_strings也不正确。 It should look like它应该看起来像

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

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

    free( strings );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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