🔴 三块要了,两块还了

👁️ 0 人浏览 💬 0 人评论 ❤️ 添加收藏

(本条路线统一用 gcc -std=c11 -O0 编译)程序自己数着账:

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

static int got = 0, gave = 0;

void *take(size_t n) { got++; return malloc(n); }
void give(void *p) { if (p) { gave++; free(p); } }

int main(void) {
    int *a = take(sizeof(int) * 2);
    int *b = take(sizeof(int) * 2);
    int *c = take(sizeof(int) * 2);

    a[0] = 1; b[0] = 2; c[0] = 3;
    int s = a[0] + b[0] + c[0];

    give(a);
    give(c);          /* b 忘了还 —— 这就是泄漏 */

    printf("%d/%d/%d/%d\n", s, got, gave, got - gave);
    give(b);
    return 0;
}
提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论