读写用malloc内存未定义过吗? [英] read before write is undefined with malloced memory?

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

问题描述

据<一个href=\"http://www.reddit.com/r/programming/comments/pfe6y/using_uninitialized_memory_for_fun_and_profit/\">this reddit的评论跟帖,如果​​试图之前已写入读取内存中是不确定的。我指的是正常的堆内存已成功的malloc 编辑。

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:编译器/运行系统允许所谓的陷阱再度presentations,这导致在访问未定义行为初始化未初始化的内存

... 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)不确定的值:要么未指定的值或陷阱重新presentation

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

这是陷阱重新presentation通过的非字符阅读的类型为未定义行为:

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

(C99,6.2.6.1p5)某些对象重新presentations不必重新present对象类型的值。如果一个对象的存储值具有这样的重presentation和是由不具有字符类型左值前pression阅读,其行为是不确定的。[...]这样的重presentation被称为陷阱重新presentation。

(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."

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

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