H
Holger Hasselbach
[Annex J.2 Undefined behavior]
- The value of the object allocated by the malloc function is used
(7.20.3.3).
- The value of any bytes in a new object allocated by the realloc
function beyond the size of the old object are used (7.20.3.4).
Something like this (include and checkings omitted):
p = malloc(sizeof(*p) * 5);
p[0] = 1; p[1] = 1; p[2] = 1;
a = p[4];
is obviously undefined, because p[4] was not initialised. But what
happens for the "hidden" read access when realloc'ing the memory:
p = malloc(sizeof(*p) * 5);
p[0] = 1; p[1] = 1; p[2] = 1;
p = realloc(p, sizeof(*p) * 10);
where p[3] and p[4] are moved to the new memory location, when it is a
new location, of course? The same applies for memmove and memcpy.
My assumptions are:
- The values of the bytes are not "used" in the sense of the above
definition for undefined behavior.
- The library functions do their work on arrays of bytes, which is
always well defined for any object type even for indeterminate values.
OTOH, there is no exception in the above definition: "value of any
bytes [...] are used".
- Thinking of it, the same would apply for the padding inside structs
that could only be initialised by accessing the struct as an array of
bytes. OTOH, there could be a deeper reason for the existence of
calloc()...
What do you mean?
Holger
- The value of the object allocated by the malloc function is used
(7.20.3.3).
- The value of any bytes in a new object allocated by the realloc
function beyond the size of the old object are used (7.20.3.4).
Something like this (include and checkings omitted):
p = malloc(sizeof(*p) * 5);
p[0] = 1; p[1] = 1; p[2] = 1;
a = p[4];
is obviously undefined, because p[4] was not initialised. But what
happens for the "hidden" read access when realloc'ing the memory:
p = malloc(sizeof(*p) * 5);
p[0] = 1; p[1] = 1; p[2] = 1;
p = realloc(p, sizeof(*p) * 10);
where p[3] and p[4] are moved to the new memory location, when it is a
new location, of course? The same applies for memmove and memcpy.
My assumptions are:
- The values of the bytes are not "used" in the sense of the above
definition for undefined behavior.
- The library functions do their work on arrays of bytes, which is
always well defined for any object type even for indeterminate values.
OTOH, there is no exception in the above definition: "value of any
bytes [...] are used".
- Thinking of it, the same would apply for the padding inside structs
that could only be initialised by accessing the struct as an array of
bytes. OTOH, there could be a deeper reason for the existence of
calloc()...
What do you mean?
Holger