在不同函数中调用 malloc 时发生内存泄漏

发布于 2025-01-15 10:01:51 字数 330 浏览 5 评论 0原文

代码看起来像这样

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无法回应 2025-01-22 10:01:51

您正在按值传递指针,当您退出函数时,malloc 返回的指针会丢失,对代码的更正应该是

void otherfunc(char** str) {
    *str = malloc(128);
    // Initialize str to something
}

void mainfunc() {
    char* foo = NULL;
    
    otherfunc(&foo);
    
    free(foo);
}

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

void otherfunc(char** str) {
    *str = malloc(128);
    // Initialize str to something
}

void mainfunc() {
    char* foo = NULL;
    
    otherfunc(&foo);
    
    free(foo);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文