J
James Kuyper
Wojtek Lerch wrote:
....
Because it's explicitly stated that the memory allocated by malloc() is
suitable for storing an object of any type, including in particular an
int[4]. I believe that the following code does not violate 6.5.6p8:
void *pv = malloc(4*sizeof(int));
int *pi = pv;
int (*pa)[2] = pv;
pi[3] = 5;
pa[1][1]==5;
But that the following does violate it:
pi = pa[0];
pi[3] = 3;
6.5.6p8 allows the pa[0] expression to return a pointer that is tagged
with a valid range that extends from (int*)pv to (int*)pv + 1. The same
is not true for the expression (int*)pv, since it is not derived from an
array declaration.
....
On the other hand, consider this:
int *ptr = malloc( 4 * sizeof(int) );
There's no expression or declaration involving an array of four ints in this
line of code. Does that mean that ptr points to a single int and adding
three to it invokes undefined behaviour? If not, why not?
Because it's explicitly stated that the memory allocated by malloc() is
suitable for storing an object of any type, including in particular an
int[4]. I believe that the following code does not violate 6.5.6p8:
void *pv = malloc(4*sizeof(int));
int *pi = pv;
int (*pa)[2] = pv;
pi[3] = 5;
pa[1][1]==5;
But that the following does violate it:
pi = pa[0];
pi[3] = 3;
6.5.6p8 allows the pa[0] expression to return a pointer that is tagged
with a valid range that extends from (int*)pv to (int*)pv + 1. The same
is not true for the expression (int*)pv, since it is not derived from an
array declaration.