内存泄漏与二维字符数组

huangapple go评论90阅读模式
英文:

Memory Leak with 2D Char Array

问题

  1. 我正在尝试释放一个二维字符数组,但当我使用`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?

  1. struct Item {
  2. char* line;
  3. struct Item *next;
  4. };
  5. void mainMethod(Item *firstArgument) {
  6. // Create 2d array
  7. int r = 5; // r gets some number
  8. char **myargs = malloc((r+1)* sizeof(char *));
  9. myargs[0] = malloc((strlen(command)+1) * sizeof(char));
  10. myargs[0] = command;
  11. int i = 1;
  12. struct Item* arg = firstArgument-&gt;next;
  13. for ( ; i &lt; r; i++) {
  14. myargs[i] = malloc(((strlen(arg-&gt;line)+1)*sizeof(char)));
  15. strcpy(myargs[i], arg-&gt;line);
  16. arg = arg-&gt;next;
  17. }
  18. myargs[i] = NULL;
  19. // do processing ...
  20. // Free 2d array
  21. int i = 0;
  22. while (i &lt;= r) {
  23. char* innerArr = arr[i];
  24. free(innerArr);
  25. i++;
  26. }
  27. free(arr);
  28. }

答案1

得分: 1

  1. 这段代码分配了一个字符串,然后用`command`的地址替换它:

myargs[0] = malloc((strlen(command)+1) * sizeof(char));
myargs[0] = command;

  1. 泄漏了已分配的内存。如果你不需要拷贝,只需使用第二行;如果你需要拷贝,可以选择以下两种方式之一:

strcpy(myargs[0], command);

  1. 或者将两行都替换为:

myargs[0] = strdup(command);

  1. 像往常一样,你应该检查分配是否失败。`sizeof(char)` 被定义为 `1`,所以你可以省略它。
英文:

This allocates a string then replaces it with the address of command:

  1. myargs[0] = malloc((strlen(command)+1) * sizeof(char));
  2. 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:

  1. strcpy(myargs[0], command);

Or replace both lines with:

  1. 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.

huangapple
  • 本文由 发表于 2023年2月19日 07:51:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497146.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定