为什么C代码可以作为Win32构建工作但是作为x64构建失败?

Bar*_*vel 2 c malloc heap-memory visual-studio-2010 dynamic-memory-allocation

我在Windows 7 - 64位,使用VS2010.下面的代码在Win32中构建没有问题并产生预期的结果(两个矩阵为8乘8,所有元素的值为1,第三个8乘8矩阵显示内存地址).

#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;
}
Run Code Online (Sandbox Code Playgroud)

但是,在尝试x64构建时,我在输出窗口中看到以下错误消息:

'test.exe':已加载'C:\ My code\test\x64\Debug\test.exe',已加载符号.

'test.exe':加载'C:\ Windows\System32 \ntdll.dll',无法找到或打开PDB文件

'test.exe':加载'C:\ Windows\System32\kernel32.dll',无法找到或打开PDB文件

'test.exe':加载'C:\ Windows\System32\KernelBase.dll',无法找到或打开PDB文件

'test.exe的':已加载 'C:\ WINDOWS\SYSTEM32\msvcr100d.dll',加载符号.

检测到严重错误c0000374 Windows在test.exe中触发了断点.

这可能是由于堆的损坏,这表明test.exe或它已加载的任何DLL中的错误.

这也可能是由于用户在test.exe具有焦点时按下F12.

如果我为Win32正确分配,使用和释放内存,为什么x64会有所不同?

Yan*_*min 5

您的指针数组大小错误.它是一个阵列int*但你只是为一个分配空间int.sizeof(int) != sizeof(int*)