我在函数中分配内存,并返回char*,我应该如何释放它?

leg*_*011 3 c malloc free pointers lifetime

如果我想在函数中分配内存:

char* allocate() {
    char *cp = (char*)malloc(10);
    ...
    return cp;
}
Run Code Online (Sandbox Code Playgroud)

我可以使用cp从中返回的内容main()吗?以及如何免费cp

Spi*_*rix 5

我可以在main()中的cp中使用返回的内容吗?

是的你可以.

以及如何释放cp?

运用

free(cp); // Replace cp with the name of the pointer if you are using it in another function
Run Code Online (Sandbox Code Playgroud)


此外,您不应该malloc在C中强制转换(和族)