Defect Report #072

Submission Date: 03 Dec 93
Submittor: WG14
Source: Clive Feather
Item 9 - definition of object
Consider the following translation unit:
#include <stdlib.h>

typedef double T;
struct hacked
int size;
T data [1];

struct hacked *f (void);
T *pt;
struct hacked *a;
char *pc;

a = malloc (sizeof (struct hacked) + 20 * sizeof (T));
if (a == NULL)
return NULL;
a->size = 20;

Method 1 /*
a->data [8] = 42; /*
Line A /*

Method 2 /*
pt = a->data;
pt += 8; /*
Line B /*
*pt = 42;

Method 3 /*
pc = (char *) a;
pc += offsetof (struct hacked, data);
pt = (T *) pc; /*
Line C /*
pt += 8; /*
Line D /*
*pt = 6 * 9;
return a;

Now, Defect Report #051 has established that the assignment on line A involves undefined behavior.
  1. Is the addition on line B strictly conforming?
    If the answer to (a) is ``yes,'' are the three statements forming ``method 2'' a valid way of implementing the struct hacked?
  2. Is the cast of line C strictly conforming?
  3. Is the addition on line D strictly conforming?
  4. If the answer to (c) and (d) are ``yes,'' are the five statements forming ``method 3'' a valid way of implementing the struct hacked?

    Now suppose that the definition of type T is changed to char. This means that the last bullet in subclause 6.3 (``an object shall have its stored value accessed only by ... a character type'') now applies, and furthermore it means that the location accessed is an integral multiple of sizeof(T) bytes from the start of the malloced object, and so constitutes an element of that object when viewed as an array of T.

  5. Is the assignment on line A now strictly conforming?
  6. What are the answers to questions (a) to (e) with this change?
a) Defect Report #051 provides the rationale for why Line A results in undefined behavior. The same rules also apply to the assignment to pt; thus Line B results in undefined behavior
b) Not applicable given the answer to question (a).
c) Assignment causes the base address of the structure to be assigned to pc. The response to Defect Report #044, question 1, states that use of the offsetof macro does not result in undefined behavior. The second line causes pc to point to member data. Line C does not contain any construct that would result in the program not being strictly conforming.
d) Line D results in undefined behavior. See answer (a) for rationale.
e) Not applicable given answers (c) and (d).
f) Subclause 6.3 contains additional restrictions, not permissions.
g) The answers to questions (a)-(e) are not affected if T has char type.
Previous Defect Report < - > Next Defect Report