因错误而退出程序时,我应该释放所有的mallocated内存吗?
something = (char**) malloc (x * sizeof(char*));
for (i = 0; i < x; i++)
something[i] = (char*) malloc (y + 1);
...
if (anything == NULL) {
printf("Your input is wrong!");
// should I free memory of every mallocated entity now?
exit(1);
}
else {
// work with mallocated entities
...
free(something); // it must be here
system("pause);
}
Run Code Online (Sandbox Code Playgroud) 我如何(m)在另一个函数中分配字符串?我已经尝试过2种方式(在代码中只是示例 - 我不会用argv做).
void someFunction(char* string, char** argv) {
string = (char*)malloc(strlen(argv[2]) + 1);
strcpy(string,argv[2]);
// string[strlen(argv[2]) + 1] = '\0' //should I do this now?
printf("%s",string); //outputs string (works fine)
}
int main(int argc, char** argv) {
char *string;
char *string2;
someFunction(string,argv);
printf("%s",string); //outputs (null)
free(string);
someFunction(&*string2,argv);
printf("%s",string2); //outputs (null)
free(string2);
}
Run Code Online (Sandbox Code Playgroud)
我想在main中使用"string",但是在不同的函数中使用mallocate.
谢谢!