C++ character array allocation error
I have a function designed to get a file's contents:
bool getFileContents(std::string loc, std::string &code) {
std::ifstream file(loc.c_str());
if(!file.is_open())
return err("Source file could not be read");
int length;
file.seekg(0, std::ios::end);
length = file.tellg();
file.seekg(0, std::ios::beg);
char *buffer = new char[length];
file.read(buffer, length);
code = buffer;
delete[] buffer;
file.close();
return true;
}
When I run this function, the file's length is always retrieved accurately. However, if I call the function once with a file, call it again with a nonexistent file, then call it one more time with the original file, the character string 'buffer' is larger than the int 'length'.
Well, that may not be accurate, rather - when the string 'buffer' is copied to the string 'code', 'code' is l开发者_StackOverflow中文版onger than 'length'. 'code' is, in each instance, instantiated immediately before the call to 'getFileContents', so it's not a matter of a previous value.
This also seems to occur if I retrieve the contents of a file, subsequently add or remove some text from the file, and retrieve the same file's contents again.
I have little experience with character strings, and figure that I'm not using them correctly, but the code I'm using came from an example, and I can't for the life of me find anything wrong with it.
Thanks for any help, Wyatt
Well, the problem is that code = buffer
relies on a NUL (\0) character to know where the buffer ends. You may be getting the NUL character by chance sometimes (esp. when the program has just started), but not always. Hence the intermittent behaviour.
Try replacing code = buffer
with code = std::string(buffer, length)
.
Apart of the \0 problem described by aix, you do double allocation, which is not necessary here and unsafe (it might be an exception before delete
, and you'll have a memory leak). Instead, you can allocate the buffer inside the string, as follows:
code.resize(length);
file.read(&code[0], length);
And don't forget to check the return value of read
. It is not guaranteed that all length
bytes will be read in one step.
精彩评论