在不同函数中调用 malloc 时发生内存泄漏
代码看起来像这样
void otherfunc(char* str) {
str = malloc(128);
// Initialize str to something
}
void mainfunc() {
char* foo = NULL;
otherfunc(foo);
free(foo);
}
理想情况下, foo
应该被释放,对吧?我不确定为什么会泄漏。 另外,如果我将 free()
移动到 otherfunc
它不会泄漏。
The code looks something like this
void otherfunc(char* str) {
str = malloc(128);
// Initialize str to something
}
void mainfunc() {
char* foo = NULL;
otherfunc(foo);
free(foo);
}
Ideally, foo
should be freed, right? I'm not sure why this is leaking.
Also, if I move the free()
to otherfunc
it does not leak.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在按值传递指针,当您退出函数时,malloc 返回的指针会丢失,对代码的更正应该是
You are passing the pointer by value, the pointer returned by malloc is lost when you exit the function, a correction to your code should be