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

标签 c pointers malloc free lifetime

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

char* allocate() {
    char *cp = (char*)malloc(10);
    ...
    return cp;
}

我可以在 main()cp 中使用返回的内容吗?以及如何释放 cp

最佳答案

can I use the returned content in cp in main()?

是的,你可以。

and how to free cp?

使用

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


还有,你should not cast the result of malloc(and family) in C

关于c - 我在函数中分配内存,并返回 char*,我应该如何释放它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29939725/

相关文章:

c - 找到一个超过第 80 个百分位数的值?

c - C 中负奇实数的黎曼 Zeta 函数

c++ - glDrawElements 只绘制半个四边形

python - 如何为双指针结构参数应用 SWIG 类型映射

c - 如何释放c中指针的内存

c - 疯狂是免费的()

c - 哪种数据结构在 C 中被广泛使用?

c - C中存储字符串的指针数组

c - 在不同函数中分配的 Realloc 指针

c++ - 两个字符串文字具有相同的指针值?