c - C - 使用 malloc、realloc 和 free。我的内存泄漏太多了,怎么了?
问题描述
所以,我的目标是定义一个结构,其中有 -
- 命令名称(例如 - “打印”)
- 命令参数计数器
- 包含参数的字符串数组。
您可以查看我的代码,但我真的很难理解我做错了什么 -
- 我使用 malloc 动态设置 my_struct.command 大小
- 我使用 malloc 动态设置 my_struct.arguments 数组大小
- 我使用 realloc 为我设置的每个参数动态增加 my_struct.arguments 大小
- 我使用 malloc 动态设置 my_struct.arguments[i] 大小
- 我最后调用 cleanup() 来释放任何动态分配的指针。
我不断收到很多内存泄漏。但我不明白为什么。
帮助和提示将不胜感激。
#include <stdio.h>
#include <stdlib.h>
struct {
char *command;
int arguments_count;
char **arguments;
} my_struct;
void cleanup(void);
int main() {
int i;
my_struct.command = (char *)malloc(6*sizeof(char));
my_struct.command = "print";
my_struct.arguments_count = 1;
my_struct.arguments = (char **)malloc(sizeof(char *));
my_struct.arguments[0] = "hello";
for(i = 1 ; i < 10; i++) {
my_struct.arguments = (char **)realloc(my_struct.arguments, sizeof(char *)*(i+1));
my_struct.arguments[i] = (char *)malloc(8*sizeof(char));
my_struct.arguments[i] = "hello";
my_struct.arguments_count++;
}
printf("Arguments count is: %d\n", my_struct.arguments_count);
printf("The arguments are:\n");
for(i = 0; i < 10; i++) {
printf("%s\n", my_struct.arguments[i]);
}
cleanup();
exit(0);
}
void cleanup(void) {
int i;
for(i = 0; i < 10; i++)
free(my_struct.arguments[i]);
free(my_struct.arguments);
free(my_struct.command);
}
解决方案
strdup - strdup() 函数返回一个指向新字符串的指针,该字符串是字符串 s 的副本。新字符串的内存使用malloc获得,并且可以使用free释放。
my_struct.command = strdup("print");
my_struct.arguments_count = 1;
my_struct.arguments = (char**) malloc(sizeof(char*));
my_struct.arguments[0] = strdup("hello");
for (int i=1; i < 10; ++i) {
// if the number of args is known, allocate before entering the loop
my_struct.arguments = (char**) realloc(my_struct.arguments, sizeof(char*)*(i+1));
my_struct.arguments[i] = strdup("hello");
my_struct.arguments_count++;
}
// in your cleanup use the arguments_count var instead of the literal 10
for (int i=0; i < my_struct.arguments_count; ++i)
你的错误是:
// allocate a memory block of 6 bytes
// assign the address of that block to command
my_struct.command = malloc(6);
// then you assigned the address of the string 'print' to command
// therefore the previous allocated block is lost -> mem leak
my_struct.command = "print";
// strdup does the following
return memcpy(malloc(strlen(str) + 1), str, strlen(str) + 1);
推荐阅读
- c# - Linq 接口列表,接口有成员字符串数组,我想要 linq 语句聚合对象数组中的所有字符串
- python - 即使在 Python 中将值重新分配给字符串后,替换方法也不起作用
- java - Java 鼠标适配器
- node.js - fork other 的包,修改它,然后提交到 npmjs.com。package.json怎么写才合适?
- javascript - Scrape Genius 歌词
- angular - 使用 ngTemplateOutlet 或其他方式在多个选项卡中重用 Angular ngb-tabs 的内容
- java - 黄瓜 - 生成错误的缺失步骤
- javascript - MaterialUI 在 onclick 事件后显示另一个视图
- vue.js - 如何使用 Axios 和 Google 电子表格 API 访问我的 Vue.js 项目中的谷歌电子表格数据?
- for-loop - 循环输出的 Jenkins 管道以单个字母而不是项目返回