写前读未定义分配内存? [英] read before write is undefined with malloced memory?

查看:39
本文介绍了写前读未定义分配内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 此 reddit 评论线程,如果尝试在写入之前读取内存.我指的是已成功 malloced.

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 malloced.

...请注意,这不是严格有效的 C:允许编译器/运行时系统使用所谓的陷阱表示来初始化未初始化的内存,这会导致访问时出现未定义的行为.

... note that this is not strictly valid C: the compiler/runtime system is allowed to initialize uninitialized memory with so-called trap representations, which cause undefined behavior on access.

我觉得这很难相信.有标准报价吗?

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, 7.20.3.3) "The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate."

关于不确定值:

(C99, 3.17.2p1) "不确定值:未指定值或陷阱表示"

(C99, 3.17.2p1) "indeterminate value: either an unspecified value or a trap representation"

关于通过非字符类型读取的陷阱表示是未定义的行为:

on trap representation reading through a non-character type being undefined behavior:

(C99, 6.2.6.1p5) 某些对象表示不需要表示对象类型的值.如果对象的存储值具有这样的表示并且由不具有字符类型的左值表达式读取,行为未定义.[...] 这种表示称为陷阱表示."

(C99, 6.2.6.1p5) "Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. [...] Such a representation is called a trap representation."

这篇关于写前读未定义分配内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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