gpt4 book ai didi

c - 在分配的内存范围之外写入时没有错误

转载 作者:行者123 更新时间:2023-11-30 21:18:47 25 4
gpt4 key购买 nike

我的main.c内容:

int main(int argc, char **argv)  
{
void * tmp = malloc(8);
((double *)tmp)[0] = 100;
((double *)tmp)[1] = 102;
printf("tmp %p\n", tmp);
printf("tmp[0] %d %f %p\n", sizeof(((double *)tmp)[0]), ((double *)tmp)[0], &((double *)tmp)[0]);
printf("tmp[1] %d %f %p\n", sizeof(((double *)tmp)[1]), ((double *)tmp)[1], &((double *)tmp)[1]);
return EXIT_SUCCESS;
}
<小时/>
=========================OUTPUT=========================  
tmp 0xee8010
tmp[0] 8 100.000000 0xee8010
tmp[1] 8 102.000000 0xee8018
========================================================

首先,我在变量 tmp 中分配了 8 个字节的内存,并将数字 100 分配给地址 0xee8010。

((double *)tmp)[0] = 100;  

我还将编号 102 分配给未分配的内存 0xee8018。

((double *)tmp)[1] = 102;  

但是我在构建时和运行时都没有看到任何错误消息。为什么不呢?

请帮我理解这一点。谢谢。

最佳答案

写入未分配的内存或超出已分配内存的范围会导致 Undefined Behavior(UB) 这并不一定会导致崩溃。
未定义的行为意味着可以观察到任何行为,当 UB 发生时,编译器实现不需要执行任何特定操作(如您所期望的段错误)。

But I didn't see any error message at the build time and runtime.

如果代码不符合语言标准,则会出现编译时错误。在这种情况下,代码遵守语言标准,但执行的操作的结果未由语言标准定义。

关于c - 在分配的内存范围之外写入时没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14382094/

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