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

IIS Log Analyzer

iis iis-7 iis-6

I want to analyze the IIS logs for a website for things like hits, keywords, countries accessed from etc.

Creating UTC time in momentjs is returning weird results

javascript datetime momentjs

I am tearing my hear off on a Monday evening! Can anyone please help me understand the problem below?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.