这个 malloc/free 对是否泄漏内存?

ntk*_*138 0 c malloc free memory-leaks

我是 C 新手。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void demo() {
    char* s = malloc(10);
    strcpy(s, "foo");
    free(s);
}

int main()
{
    demo();
}
Run Code Online (Sandbox Code Playgroud)

这个程序会泄漏几个字节的内存吗?

gsa*_*ras 8

这个程序会泄漏几个字节的内存吗?

free(s)将取消分配char* s = malloc(10);本示例中动态分配的所有内存。

正如 @Alexander 评论的那样:“您担心 的最后 6 个字符吗s?(超过 的末尾"foo")不用担心,free()将释放 的整个分配s,无论您如何使用它或在其中放入什么”


好读:什么是内存泄漏?

  • 抱歉,我读了 strdup,我的错误:-( (2认同)