Search code examples
c++visual-studio-2010access-violation

"Access violation writing location" with file.getline? (Only in release build)


getting this error in an application written in C++ (VS 2010):

Unhandled exception at 0x77648da9 in divt.exe: 0xC0000005: Access violation writing location 0x00000014.

it points to this function in free.c:

void __cdecl _free_base (void * pBlock)
{

        int retval = 0;


        if (pBlock == NULL)
            return;

        RTCCALLBACK(_RTC_Free_hook, (pBlock, 0));

        retval = HeapFree(_crtheap, 0, pBlock);
        if (retval == 0) //<-----------------------right here
        {
            errno = _get_errno_from_oserr(GetLastError());
        }
}

Via debugging I was able to determine where its actually crashing:

void MenuState::LoadContentFromFile(char* File,std::string &Content)
{
    std::string strbuf;

    char buffer[1028];

    std::fstream file;
    file.open(File,std::ios_base::in);

    if(file.fail()) 
    {
        Content = ErrorTable->GetString("W0001");
        return;
    }
    if(file.is_open())
    {
        while(!file.eof())
        {
            file.getline(buffer,128,'\n');  // <----here
            strbuf = buffer;
            Content += strbuf + "\n";
        }
    }

    file.close();

    strbuf.clear();
}

It crashes on file.getline(buffer,128,'\n');

I don't understand why but it's only doing it in release build (Optimizations turned off), on debug build its working fine.

Any Ideas?


Solution

  • Asked a friend for help, we came up with this Solution:

    std::string strbuf;
    
    char buffer[256] = "\0";
    
    FILE* f = fopen(File, "rt");
    
    while(fgets(buffer,sizeof(buffer),f) != NULL)
    {
        Content += buffer;
    }
    
    fclose(f);
    strbuf.clear();
    

    Works fine, still thanks for your efforts.