我是C和StackOverflow的新手。

我正在尝试在Visual Studio-2015中实现针对此问题http://stackoverflow.com/questions/34624027/how-to-create-a-fast-huge-union-array-without-wasting-memory-in-c的解决方案。以下是我的代码:

#include "stdafx.h"

#include "malloc.h"
#include "inttypes.h"

#define RESERVED_BYTES 2147483648

typedef union {
    void *pv;
    char *pc;
    uint8_t *pu8;
    uint16_t *pu16;
} parray_type;

int main()
{
    parray_type parray;
    parray.pv = calloc(RESERVED_BYTES, 1);

    // last element in allocated buffer for each type
    char c = parray.pc[RESERVED_BYTES - 1];
    uint8_t u8 = parray.pu8[RESERVED_BYTES - 1];
    uint16_t u16 = parray.pu16[RESERVED_BYTES / 2 - 1];

    // first element in allocated buffer for each type
    char c_2= parray.pc[0];
    uint8_t u8_2 = parray.pu8[0];
    uint16_t u16_2 = parray.pu16[0];

    printf("c='%c' (%d)  u8='0x%x' (%d) u16='%h' (%d)\n", c, c, u8, u8, u16, u16);
    printf("c='%c' (%d)  u8='0x%x' (%d) u16='%h' (%d)\n", c_2, c_2, u8_2, u8_2, u16_2, u16_2);

    return 0;
}


它编译正常,但是当我尝试运行它时,我在char c = parray.pc[RESERVED_BYTES - 1];的赋值中收到以下错误。错误是Unhandled exception at 0x012717F8 in TstLrgArr.exe: 0xC0000005: Access violation reading location 0x7FFFFFFF.当我注释掉分配c,u8和u16的三行时,我在分配c_2时遇到了相同的错误,只是访问冲突是读取位置0x00000000。

我认为预期的输出为以下两行:
c='' (0) u8='0x00' (0) u16='' (0)

我做错了什么,还是这是VS-2015的限制?

最佳答案

calloc可以分配的最大大小取决于您所运行的平台。您的数组大小可能远大于#define RESERVED_BYTES 2147483648calloc可能会返回NULL

将NULL指针测试添加到您的代码中。

 parray.pv = calloc(RESERVED_BYTES, 1);
 if ( parray.pv == NULL )
 {
     // ... add print error ...
     return 0;
 }

10-08 12:58