在分配的内存范围之外写入时没有错误 [英] No errors when writing outside allocated memory range

查看:105
本文介绍了在分配的内存范围之外写入时没有错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的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个字节的内存,并为地址0xee8010分配了数字100.

First, I did allocate 8 bytes of memory in variable tmp and I assigned number 100 to address 0xee8010.

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

我还将数字102分配给未分配的内存0xee8018.

I also assign number 102 to unallocated memory 0xee8018.

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

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

But I didn't see any error message at build-time nor at runtime. Why not?

请帮助我理解这一点. 谢谢.

Please help me understand this. Thank you.

推荐答案

写为未分配或超出分配的内存范围写入会导致

Writing to unallocated or writing beyond bounds of allocated memory results in Undefined Behavior(UB) which does not necessarily warrant a crash.
An Undefined behavior means that any behavior can be observed the compiler implementation does not need to do anything specific(like a segmentation fault as you expect) when an UB occurs.

但是在构建时和运行时我没有看到任何错误消息.

对于不符合语言标准的代码,您将获得编译时错误.在这种情况下,代码会遵守语言标准,但会执行某些结果,但语言标准并未对此进行定义.

You get compile time errors for code which do not abide to the language standard. In this case the code abides to the language standard but does something who's outcome is not defined by the language standard.

这篇关于在分配的内存范围之外写入时没有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆