You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C、Rust程序内存无法正常释放,而C++无此问题?

为什么C和Rust程序内存无法被系统正常释放,但C++程序无此问题?

先看以下三段测试代码:

C代码

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

void *thread_function(void *arg) {
    char **records = malloc(1000000 * sizeof(char *));
    if (records == NULL) {
        perror("Memory allocation failed");
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < 1000000; ++i) {
        records[i] = malloc(16);
        if (records[i] == NULL) {
            perror("Memory allocation failed");
            exit(EXIT_FAILURE);
        }
        sprintf(records[i], "%d", i);
    }

    printf("done\n");

    for (int i = 0; i < 1000000; ++i) {
        free(records[i]);
    }
    free(records);

    pthread_exit(NULL);
}

int main() {
    pthread_t threads[400];

    for (int i = 0; i < 400; ++i) {
        if (pthread_create(&threads[i], NULL, thread_function, NULL) != 0) {
            perror("Thread creation failed");
            exit(EXIT_FAILURE);
        }
    }

    for (int i = 0; i < 400; ++i) {
        pthread_join(threads[i], NULL);
    }

    while (1) {
      sched_yield();
    }

    return 0;
}

Rust代码

fn main() {
    for _ in 0..400 {
        std::thread::spawn(|| {
            let mut records: Box<Vec<String>> = Box::default();
            for i in 0..1_000_000 {
                let record = i.to_string();
                records.push(record);
            }
            println!("done");
        });
    }

    loop {
        std::thread::yield_now();
    }
}

C++代码

#include <iostream>
#include <thread>
#include <vector>

int main() {
  for (int i = 0; i < 1600; ++i) {
    std::thread([=]() {
      std::vector<std::string> records;
      for (int i = 0; i < 1000000; ++i) {
        std::string record = std::to_string(i);
        records.push_back(record);
      }
      std::cout << "done" << std::endl;
    }).detach();
  }

  while (true) {
    std::this_thread::yield();
  }

  return 0;
}

观察到的现象

用top工具(以及Mac内置监控)查看内存占用:

  • C和Rust程序运行到无限循环代码块时,内存未被正常回收,仍有数百MB的内存被占用;
  • C++程序的内存占用始终很低,通常仅为几MB。

已有猜测与疑问

我调研数日,猜测可能与内存碎片、过度内存释放或分配器缓存(调用系统接口分配内存存在开销)有关,但尚未找到有说服力的答案。

我在系统编程方面经验有限,是否存在未掌握的关键知识?另外,只有当线程数足够高时(最好略低于被系统终止的阈值)才会触发内存释放异常,线程数较低时则无此问题。若尝试本地复现,建议调整线程数进行测试。


内容的提问来源于stack exchange,提问作者xhwhis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 11:30:14