【发布时间】:2010-09-26 07:32:27
【问题描述】:
我在我的应用程序中输入了一个 200mb 的文件,由于一个非常奇怪的原因,我的应用程序的内存使用量超过了 600mb。我尝试过vector和deque,以及std::string和char *,但都无济于事。我需要我的应用程序的内存使用与我正在阅读的文件几乎相同,任何建议都会非常有帮助。 是否存在导致如此多内存消耗的错误?你能指出问题还是我应该重写整个事情?
Windows Vista SP1 x64、Microsoft Visual Studio 2008 SP1、32 位发行版、Intel CPU
到目前为止的整个应用程序:
#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <time.h>
static unsigned int getFileSize (const char *filename)
{
std::ifstream fs;
fs.open (filename, std::ios::binary);
fs.seekg(0, std::ios::beg);
const std::ios::pos_type start_pos = fs.tellg();
fs.seekg(0, std::ios::end);
const std::ios::pos_type end_pos = fs.tellg();
const unsigned int ret_filesize (static_cast<unsigned int>(end_pos - start_pos));
fs.close();
return ret_filesize;
}
void str2Vec (std::string &str, std::vector<std::string> &vec)
{
int newlineLastIndex(0);
for (int loopVar01 = str.size(); loopVar01 > 0; loopVar01--)
{
if (str[loopVar01]=='\n')
{
newlineLastIndex = loopVar01;
break;
}
}
int remainder(str.size()-newlineLastIndex);
std::vector<int> indexVec;
indexVec.push_back(0);
for (unsigned int lpVar02 = 0; lpVar02 < (str.size()-remainder); lpVar02++)
{
if (str[lpVar02] == '\n')
{
indexVec.push_back(lpVar02);
}
}
int memSize(0);
for (int lpVar03 = 0; lpVar03 < (indexVec.size()-1); lpVar03++)
{
memSize = indexVec[(lpVar03+1)] - indexVec[lpVar03];
std::string tempStr (memSize,'0');
memcpy(&tempStr[0],&str[indexVec[lpVar03]],memSize);
vec.push_back(tempStr);
}
}
void readFile(const std::string &fileName, std::vector<std::string> &vec)
{
static unsigned int fileSize = getFileSize(fileName.c_str());
static std::ifstream fileStream;
fileStream.open (fileName.c_str(),std::ios::binary);
fileStream.clear();
fileStream.seekg (0, std::ios::beg);
const int chunks(1000);
int singleChunk(fileSize/chunks);
int remainder = fileSize - (singleChunk * chunks);
std::string fileStr (singleChunk, '0');
int fileIndex(0);
for (int lpVar01 = 0; lpVar01 < chunks; lpVar01++)
{
fileStream.read(&fileStr[0], singleChunk);
str2Vec(fileStr, vec);
}
std::string remainderStr(remainder, '0');
fileStream.read(&remainderStr[0], remainder);
str2Vec(fileStr, vec);
}
int main (int argc, char *argv[])
{
std::vector<std::string> vec;
std::string inFile(argv[1]);
readFile(inFile, vec);
}
【问题讨论】:
-
您使用的是哪个 STL?在哪台机器上?
-
一个非常非常小的文件的内存使用量是多少?
-
您知道,您不需要需要将调用打开与 fstreams 分开,您可以这样做:std::ifstream file("whatever", std:: ios::二进制);此外,当 ifstream 对象被破坏时,它也会自动关闭。所以通常你也不需要显式关闭。
-
您在 main 中的“inFile”变量也是完全没有意义的,因为 std::string 的构造函数采用 const char * 不是显式的。这意味着将 const char * 传递给采用 std::string 的函数将自动工作。
-
还有! “memcpy(&tempStr[0],&str[indexVec[lpVar03]],memSize);”对我来说看起来很调皮,我不是标准律师,但我不确定 std::string 是否保证在内部是连续的(只有 c_str/data 返回一个连续的缓冲区。
标签: c++ memory memory-leaks stl