Mat*_*att 4 c memory arrays malloc pointers
编辑:我根据人们的建议改变了我的程序,但我无法修复内存泄漏.另外,我需要在不使用argc的情况下释放它们,所以我需要以某种方式跟踪数组长度,因此我将最后一个元素标记为null.
目前我正在编写一个C程序,它将命令行参数复制到动态分配的数组中.我的代码看起来像:
char **array;
int j;
array = malloc(sizeof(char*) * (argc + 1));
int i;
int index = 0;
for(i = 0; i < (argc); i++){
int length = strlen(*(argv + i));
array[i] = malloc((length + 1) * sizeof(char));
// Cycle through all the chars and copy them in one by one
for(j = 0; j <= length; j++){
array[i][j] = toupper(argv[i][j]);
}
}
array[i + 1] = NULL;
return array;
Run Code Online (Sandbox Code Playgroud)
后来,我试着释放记忆:
char** array_copy = array;
while(*array_copy != NULL){
free(*array_copy++);
}
free(*array_copy) // free the null at the end
free(array);
Run Code Online (Sandbox Code Playgroud)
但是,我仍然得到内存泄漏.我不太确定我做错了什么.如果有人能给我一些很棒的提示.
谢谢!
你的最后一行free(array)不是释放你原来的malloc,因为你在array释放它的内容时会增加.
另外(正如其他人指出的那样):
你的循环释放数组内容是检查非零,但你不能确保元素为零开始.
当您只需要argc时,在数组中分配argc + 1个元素.
*(argv + i)是一样的argv[i].