relocation truncated to fit: R_X86_64_32 against `.bss'
Build failed: 2 error(s), 0 warning(s)
int a[99999999999999]; // 約 100 兆元素
// 內存需求:99999999999999 * 4 bytes ≈ 364 TB
.bss 段,链接器需為其分配虛擬地址空間。R_X86_64_32 表示 64 位模式下使用 32 位相對地址重定位,但 .bss 段偏移超出 32 位範圍 (4GB),導致截斷錯誤。// 仍會因內存不足拋出 std::bad_alloc
int *a = new int[99999999999999]; // 或 malloc
// 程序啟動即崩潰
#include <fstream>
#include <vector>
#include <string>
void processLargeData(const std::string& filename) {
std::ifstream file(filename, std::ios::binary);
if (!file) return;
constexpr size_t CHUNK_SIZE = 1024 * 1024; // 1M 元素 ≈ 4MB
std::vector<int> buffer(CHUNK_SIZE);
while (file) {
file.read(reinterpret_cast<char*>(buffer.data()), buffer.size() * sizeof(int));
size_t count = file.gcount() / sizeof(int);
if (count == 0) break;
// 處理 buffer[0..count-1]
processChunk(buffer.data(), count);
}
}
// 或使用內存映射文件
#include <sys/mman.h> // Linux
// Windows: CreateFileMapping + MapViewOfFile
CREATE TABLE data (id INTEGER PRIMARY KEY, value INTEGER);| 限制類型 | 32 位系統 | 64 位系統 (典型) |
|---|---|---|
| 單個靜態數組最大 | ~2-3 GB | ~256 TB (用戶空間) |
| 靜態數組重定位 | 通常無問題 | R_X86_64_32 限制 4GB 偏移 (小內存模型) |
| 動態分配最大 | ~2-3 GB | ~128 TB (受物理內存+交換分區限制) |
| 大內存模型編譯選項 | - | -mcmodel=large (GCC/Clang) 支持 >4GB 靜態數據 |
// 僅解決重定位截斷,不解決物理內存不足
g++ -mcmodel=large -fpic -o prog main.cpp
// 代碼體積增大,性能略降,但允許超大 .bss 段
int a[99999999999999] 需求 364 TB 內存,**物理上不可能**。錯誤 relocation truncated to fit 是鏈接器發現靜態段超出 32 位重定位範圍的表現。正確工程方案:**分塊讀取處理、文件映射、數據庫存儲、稀疏壓縮**,將「一次性全量內存」轉化為「流式/按需訪問」。