Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 653
Aaron McDaid Avatar asked Feb 09 '12 22:02

Aaron McDaid


1 Answers

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

like image 144
ouah Avatar answered Sep 21 '22 12:09

ouah