编辑:我根据人们的建议修改了我的程序,但是我无法修复内存泄漏问题。此外,我需要在不使用 argc 的情况下释放它们,因此我需要以某种方式跟踪数组长度,所以我将最后一个元素标记为空。
目前我正在编写一个 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;
之后,我尝试释放内存:
char** array_copy = array;
while(*array_copy != NULL){
free(*array_copy++);
}
free(*array_copy) // free the null at the end
free(array);
然而,我仍然遇到了内存泄漏问题。我不太确定我做错了什么。如果有人能给我一些提示,那就太好了。
谢谢!
argc + 1
?你只需要argc
次。此外,你的deletewhile
循环是有问题的。始终保持对数组大小的计数。 - pmr