相关疑难解决方法(0)

为什么 GCC 的 ifstream >> 双分配这么多内存?

我需要从一个以空格分隔的人类可读文件中读取一系列数字并进行一些数学运算,但是我在读取文件时遇到了一些真正奇怪的内存行为。

如果我阅读数字并立即丢弃它们......

#include <fstream>

int main(int, char**) {
    std::ifstream ww15mgh("ww15mgh.grd");
    double value;
    while (ww15mgh >> value);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我的程序根据 valgrind 分配了 59MB 的内存,相对于文件的大小线性缩放:

$ g++ stackoverflow.cpp
$ valgrind --tool=memcheck --leak-check=yes ./a.out 2>&1 | grep total
==523661==   total heap usage: 1,038,970 allocs, 1,038,970 frees, 59,302,487 
Run Code Online (Sandbox Code Playgroud)

但是,如果我ifstream >> string改为使用然后使用sscanf来解析字符串,我的内存使用情况看起来更加正常:

#include <fstream>
#include <string>
#include <cstdio>

int main(int, char**) {
    std::ifstream ww15mgh("ww15mgh.grd");
    double value;
    std::string text;
    while (ww15mgh >> text)
        std::sscanf(text.c_str(), "%lf", &value);
    return …
Run Code Online (Sandbox Code Playgroud)

c++ memory fstream libstdc++

21
推荐指数
1
解决办法
621
查看次数

标签 统计

c++ ×1

fstream ×1

libstdc++ ×1

memory ×1