Search code examples
cvisual-studio-2010mallocdynamic-memory-allocationheap-memory

Why would C code work as Win32 build but fail as x64 build?


I am on Windows 7 - 64bit, using VS2010. The following code builds in Win32 with no problems and produces the expected outcome (Two matrices of 8 by 8 with all elements having a value of 1 and a third 8 by 8 matrix showing memory addresses).

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int main(void) {
    int rows, cols, i, x, y;
    int **array_of_pointers, *arr2d;
    rows = 8;
    cols = 8;
    arr2d = (int *) malloc(rows * cols * sizeof(int));
    for(i = 0; i < rows*cols; i++) {
        *(arr2d + i) = 1;
    }

    for(y = 0; y < cols; y++) {
        printf("\n");
        for(x = 0; x < rows; x++) {
            printf("%d ",*(arr2d + y * cols + x));
        }
    }

    array_of_pointers = (int **) malloc(rows * cols * sizeof(int));
    //I want each element of this array_of_pointers to point to the corresponding     element of arr2d
    for(y = 0; y < cols; y++) {
        for(x = 0; x < rows; x++) {
            *(array_of_pointers + y * cols + x) = (arr2d + y * cols + x);
        }
    }

    //now try printing from pointer array
    printf("\n");
    for(y = 0; y < cols; y++) {
        printf("\n");
        for(x = 0; x < rows; x++) {
            printf("%d ",**(array_of_pointers + y * cols + x));
        }
    }

    //now try printing addresses from pointer array
    printf("\n");
    for(y = 0; y < cols; y++) {
        printf("\n");
        for(x = 0; x < rows; x++) {
            printf("%d ",*(array_of_pointers + y * cols + x));
        }
    }

    free(arr2d);
    free(array_of_pointers);

    _getch();
    return 0;
}

However, when trying an x64 build I am presented with the following error message in the output window:

'test.exe': Loaded 'C:\My code\test\x64\Debug\test.exe', Symbols loaded.

'test.exe': Loaded 'C:\Windows\System32\ntdll.dll', Cannot find or open the PDB file

'test.exe': Loaded 'C:\Windows\System32\kernel32.dll', Cannot find or open the PDB file

'test.exe': Loaded 'C:\Windows\System32\KernelBase.dll', Cannot find or open the PDB file

'test.exe': Loaded 'C:\Windows\System32\msvcr100d.dll', Symbols loaded.

Critical error detected c0000374 Windows has triggered a breakpoint in test.exe.

This may be due to a corruption of the heap, which indicates a bug in test.exe or any of the DLLs it has loaded.

This may also be due to the user pressing F12 while test.exe has focus.

If I have allocated, used and freed memory correctly for Win32 why would it be different for x64?


Solution

  • You're probably not be allocating enough space for array_of_pointers. You're using sizeof(int) instead of sizeof(int *). On 64-bit, I'm guessing that int is 32 bits but pointers are 64 bits.

    Additionally, you should be using %p (instead of%d) as the format specifier when printing out the elements of array_of_pointers.