Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

c - read before write is undefined with malloced memory?

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.

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If accessing through a char*, this is defined. But otherwise, this is undefined behavior.

(C99, 7.20.3.3) "The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate."

on indeterminate value:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...