2000 萬字符 ≈ 20 MB(單字節編碼)或 40 MB(UTF-16),屬於大對象分配,需關注堆內存、碎片化與分配失敗處理。
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *create_huge_string(size_t len) {
char *str = (char *)malloc(len + 1); // +1 留終止符
if (!str) {
fprintf(stderr, "內存分配失敗:請求 %zu 字節\n", len + 1);
return NULL;
}
memset(str, 'A', len); // 填充示例數據
str[len] = '\0';
return str;
}
int main() {
const size_t LEN = 20000000;
char *huge = create_huge_string(LEN);
if (huge) {
printf("分配成功,長度:%zu\n", strlen(huge));
free(huge); // 必須釋放
}
return 0;
}
#include <string>
#include <iostream>
#include <new> // std::bad_alloc
std::string create_huge_string_cpp(size_t len) {
try {
std::string s(len, 'A'); // 一次性構造
return s; // C++11 移動語義無拷貝開銷
} catch (const std::bad_alloc&) {
std::cerr << "內存不足\n";
return {};
}
}
malloc_trim(0)(glibc)或預留地址空間(Windows `VirtualAlloc`)。mmap/CreateFileMapping)。// Java 堆需設 -Xmx256m 以上
String huge = "A".repeat(20_000_000); // Java 11+
C/C++ 用堆分配(malloc/new/std::string),務必檢查返回值/捕獲異常,用完釋放,64 位環境最穩健。