英文:
Memory Leak with 2D Char Array
问题
我正在尝试释放一个二维字符数组,但当我使用`fsanitize=address`编译然后运行程序时,出现了内存泄漏。似乎代码中的`free(innerArray)`没有释放单独的字符数组。有任何想法吗?
结构 项目 {
char* 行;
结构 项目 *下一个;
};
无效 主方法(项目 *第一个参数) {
// 创建二维数组
int r = 5; // r 获取某个数字
char *myargs = malloc((r+1) sizeof(char ));
myargs[0] = malloc((strlen(command)+1) * sizeof(char));
myargs[0] = command;
int i = 1;
结构 项目 参数 = 第一个参数->下一个;
对于 ( ; i < r; i++) {
myargs[i] = malloc(((strlen(参数->行)+1)*sizeof(char)));
strcpy(myargs[i], 参数->行);
参数 = 参数->下一个;
}
myargs[i] = NULL;
// 进行处理 ...
// 释放二维数组
int i = 0;
当 (i <= r) {
char* 内部Arr = arr[i];
免费(内部Arr);
i++;
}
免费(安排);
}
英文:
I am trying to free a 2D char array but I'm getting a memory leak when I compile with fsanitize=address and then run the program. It doesn't seem like the code free(innerArray) is freeing the individual char array. Any ideas?
struct Item {
    char* line;
    struct Item *next;
};
void mainMethod(Item *firstArgument) {
   // Create 2d array
  int r = 5; // r gets some number 
  char **myargs = malloc((r+1)* sizeof(char *));
  myargs[0] = malloc((strlen(command)+1) * sizeof(char));
  myargs[0] = command;
  int i = 1;
  struct Item* arg = firstArgument->next;
  for ( ; i < r; i++) {
    myargs[i] = malloc(((strlen(arg->line)+1)*sizeof(char)));
    strcpy(myargs[i], arg->line);
    arg = arg->next;
  }
  myargs[i] = NULL;
  // do processing ...
  // Free 2d array
  int i = 0;
  while (i <= r) {
    char* innerArr = arr[i];
    free(innerArr);
    i++;
  }
  free(arr);
}
答案1
得分: 1
这段代码分配了一个字符串,然后用`command`的地址替换它:
myargs[0] = malloc((strlen(command)+1) * sizeof(char));
myargs[0] = command;
泄漏了已分配的内存。如果你不需要拷贝,只需使用第二行;如果你需要拷贝,可以选择以下两种方式之一:
strcpy(myargs[0], command);
或者将两行都替换为:
myargs[0] = strdup(command);
像往常一样,你应该检查分配是否失败。`sizeof(char)` 被定义为 `1`,所以你可以省略它。
英文:
This allocates a string then replaces it with the address of command:
  myargs[0] = malloc((strlen(command)+1) * sizeof(char));
  myargs[0] = command;
leaking the allocated memory. If you don't need the copy just use the 2nd line, and if you want a copy either do:
  strcpy(myargs[0], command);
Or replace both lines with:
  myargs[0] = strdup(command);
As always you want to check if your allocations failed. sizeof(char) is defined as 1 so you just leave it out.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论