gpt4 book ai didi

c - 为什么 mac OS X 不会在此代码中抛出运行时错误?

转载 作者:太空宇宙 更新时间:2023-11-04 05:27:45 26 4
gpt4 key购买 nike

我在 OS X 上工作。我写了一个简单的代码,比如

pTest       =   (char*)malloc(sizeof(char) * 3);

pTest[0] = 0;
pTest[1] = 1;
pTest[2] = 2;

pTest = (char*)realloc(pTest, sizeof(char) * 2);

printf("%d %d %d %d\n", pTest[0], pTest[1], pTest[2], pTest[3]);
pTest[3] = 100; // memory access violation.

如果这段代码不会造成访问冲突,为什么需要realloc?虽然我们在堆段中分配了较小的内存,但我们所要做的就是访问进一步的索引,例如 pTest[100]pTest[2048]pTest[65536]
有人可以解释为什么不会导致访问冲突吗?

最佳答案

void *realloc(void *ptr, size_t size);

The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes.

你正在缩小尺寸:

pTest   =   (char*)realloc(pTest, sizeof(char) * 2);
^
|
changed size of array to two chars only

在这个最大索引值之后可以是 1 作为 pTest[1]

任何索引值 > 1,导致内存违规 - 非法内存访问 - 运行时未定义的行为。

关于c - 为什么 mac OS X 不会在此代码中抛出运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17989617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com