小编Luc*_*fia的帖子

退出前我应该释放内存吗?

因错误而退出程序时,我应该释放所有的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)

c malloc free dynamic-allocation

20
推荐指数
4
解决办法
6239
查看次数

在另一个函数中分配字符串(char*)

我如何(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.

谢谢!

c malloc

0
推荐指数
1
解决办法
319
查看次数

标签 统计

c ×2

malloc ×2

dynamic-allocation ×1

free ×1