问题描述
根据 此 reddit 评论线程,如果尝试在写入之前读取内存.我指的是已成功 malloc
ed.
According to this reddit comment thread, it is undefined if an attempt is made to read memory before it has been written to. I'm referring to normal heap memory which has been succesfully malloc
ed.
...请注意,这不是严格有效的 C:允许编译器/运行时系统使用所谓的陷阱表示来初始化未初始化的内存,这会导致访问时出现未定义的行为.
我觉得这很难相信.有标准报价吗?
I find this hard to believe. Is there a Standard quote?
当然,我知道无法保证内存已清零.此未初始化内存中的值本质上是伪随机或任意的.但我真的不敢相信标准会将此称为未定义的行为(从某种意义上说,它可能会出现段错误,或删除所有文件,或其他任何东西).那里的其他 reddit 线程没有进一步说明这个问题.
Of course, I understand that there is no guarantee that the memory has been zeroed out. The values in this uninitialized memory are essentially pseudo-random or arbitrary. But I can't really believe that the Standard would refer to this as undefined behaviour (in the sense that it might segfault, or delete all your files, or whatever). The rest of the reddit thread there didn't cast any more light on this issue.
推荐答案
如果通过 char*
访问,这是定义的.但除此之外,这是未定义的行为.
If accessing through a char*
, this is defined. But otherwise, this is undefined behavior.
(C99, 7.20.3.3) "malloc 函数为大小由 size 指定且值不确定的对象分配空间."
关于不确定值:
(C99, 3.17.2p1) "不确定值:未指定值或陷阱表示"
关于通过非字符类型读取的陷阱表示是未定义的行为:
on trap representation reading through a non-character type being undefined behavior:
(C99, 6.2.6.1p5) 某些对象表示不需要表示对象类型的值.如果对象的存储值具有这样的表示并且由不具有字符类型的左值表达式读取,行为未定义.[...] 这种表示称为陷阱表示."
这篇关于写前读未定义分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!