c - 程序内存泄漏? C

标签 c memory valgrind

动态分配一个cstrings数组来分隔传递给它的字符串。 Valgrind 说我有 7 个分配,但只有 3 个释放。但我不确定如何在使用返回数组的函数时释放内存。

这是函数

char ** func( char * str, char del ) {
     char** substrings;
     char* word;
     int len = 0, capacity = 2, i, x;
     substrings = malloc(sizeof(char*) * (capacity + 1));
     for (i = 0; i <= capacity; i++){
         substrings[i] = NULL;
     }
     while (*word != '\0') {
         if (len  >= capacity){
             /* double size */
             char **temp;
             capacity *= 2;
             temp = malloc(sizeof(char*) * (capacity + 1));
             for (i = 0; i < len; i++) {
                 temp[i] = substrings[i];
             }
             for (i = len; i <= capacity; i++) {
                 temp[i] = NULL;
             }
             substrings = temp;

             temp = NULL;
             free(temp);

         }
     }     
     return substrings;
 }

最佳答案

根据您的代码,

if (len  >= capacity){
         /* double size */
         char **temp;
         capacity *= 2;
         temp = malloc(sizeof(char*) * (capacity + 1));
         for (i = 0; i < len; i++) {
             temp[i] = substrings[i];
         }
         for (i = len; i <= capacity; i++) {
             temp[i] = NULL;
         }
         free(substrings); // release old memory
         substrings = temp; // this line causes substrings pointer leak if you assign new address to it without free

         temp = NULL;
         free(temp); // no need free NULL

     }

实际上,如果您将 valgrind--track-origins=yes 选项一起使用,它会报告哪条线路发生泄漏。

关于c - 程序内存泄漏? C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42453032/

相关文章:

java - 运行时堆栈内存

c - 返回 char[] 以在 strtok() 函数中使用它

c - 当使用不同的文件描述符时,为什么结果不同? (系统编程)

c++ - C++是否可以自动访问机器中的所有可用内存

c - 即使在调用 fclose() 之后,由于 fopen() 而导致的内存泄漏

c - 返回字符串的内存泄漏

c++ - Valgrind 不报告 "delete array"上的内存泄漏

C编程打印一定数量的字节到屏幕

c - 简单客户端/服务器的问题,文件打印错误

iphone - 在 iOS 4.0 上使用大图像时应用程序崩溃