Search code examples
c++file-iovisual-studio-2015access-violation

Double pointer out array parameter exception


I have the following function which I intend to load shaders with (error checking removed for brevity):

unsigned int readFile(const char* file, char** buffer)
{
    FILE* fp;
    fopen_s(&fp, file, "rb");

    fseek(fp, 0, SEEK_END);
    size_t size = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    *buffer = new char[size + 1];

    fread(*buffer, 1, size, fp);
    *buffer[size] = 0; // BAD LINE, only [0] is fine.

    fclose(fp);

    return 0;
}

It is called with:

char* fileContents = nullptr;
readAllFile("test.txt", &fileContents);

I cannot figure out how to fix the bad line. When I use char*& buffer as the out parameter it works fine, and a reference in large part is functionally the same as a pointer right?

The error is:

Exception thrown at 0x011919D4 in My World_Win32_Debug.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC.

How should I set the last element of the buffer to 0 (null terminator)? I've looked through the debugger and the contents of buffer are valid, and set properly until reaching the bad line despite buffer being referenced the same way every time.

With only [0] working fine, that indicates to me I'm address only the pointer itself, not it's data, but I don't know how to address it otherwise. Every other way I've tried gives a compile error.

I'm aware that references are preferred in many cases, and there's other problems here, but I do need to know why I have the problem above first.


Solution

  • You want this:

    (*buffer)[1] = 0;
    

    instead of:

    *buffer[1] = 0;  // same as  *(buffer[1]) = 0;