Question

According to the Visual C++ runtime there is a heap corruption when calling free in the destructor. But I don't understand why there is a heap corruption, can anyone explain why? The precise error is:

CRT detected that the application wrote to memory after end of heap buffer.

Also, if I ignore the error the program doesn't crash, it keeps running and when I press a key it returns 0.

The class only contains a constructor and destructor and the private vars FILE* target and char* raw_data.

foo::foo (wchar_t* path)
{
    size_t size;

    target = _wfopen (path, L"rb+");
    if (!target) {
        char* error = strerror (errno);
        printf ("The file could not be opened: %s\n", error);
        _exit (1);
    }

    fseek (target, 0L, SEEK_END);
    size = ftell (target);
    fseek (target, 0, SEEK_SET);
    raw_data = (char*) malloc (size);
    size = fread (raw_data, 1, size, target);
    raw_data[size] = '\0';
}

foo::~foo ()
{
    fclose (target);
    free (raw_data);
}

int main ()
{
    nbt* klas = new nbt (L"C:\\Users\\Ruben\\level");
    puts ("Success?!");
    delete klas;
    getchar ();
    return 0;
}
Was it helpful?

Solution 2

One sure problem is this code:

raw_data = (char*) malloc (size);
size = fread (raw_data, 1, size, target);
raw_data[size] = '\0';

You cannot access raw_data[size], because it is beyond the allocated size. Indexed access in C/C++ is zero based. As a result, the last element of raw_data that can be accessed with your existing code is raw_data[size-1]. To be able to set the byte which is at offset size to zero you need to change your malloc to:

raw_data = (char*) malloc (size+1);

Since this is a C++ application, you may want to use streams and new/delete instead of FILE pointers and malloc/free.

OTHER TIPS

When writing the NUL terminator as you do:

raw_data[size] = '\0';

... you are using one byte more than the bytes you allocated. There may be other errors but there is definitely an error on this line -- writing to memory you have not allocated is "undefined behaviour" and could explain the crash you're observing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top