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());

        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;


    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 longer 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).

Need Your Help

VS 2008 Intellisense missing: the key combination is bound to command which is not currently available

visual-studio-2008 editor intellisense

Intellisense has stopped working for my aspx files, and I've looked at the other questions that address the issue with no solution.

unresolved names linking against library but passing obj files directly works fine?

c++ osx ld

Consider the following g++ invocation (Apple GCC 4.2.1, running on OSX 10.6.5) which works just fine:

use htaccess to show page in folder that doesn't exist


On my website, I have a user profile php file, where if you write http://www.youdomain.com/user.php?id=[user id], it shows that user's profile with that id.