...
Code Block | ||
---|---|---|
| ||
struct flexArrayStruct { int num; int data[1]; }; /* ... */ size_t array_size; size_t i; /* Spaceinitialize array_size */ /* space is allocated for the struct */ struct flexArrayStruct *structP = (struct flexArrayStruct *) malloc(sizeof(struct flexArrayStruct) + sizeof(int) * (ARRAYarray_SIZEsize - 1)); if (structP == NULL) { /* handle malloc failure */ } structP->num = SOME_NUMBER0; /* Accessaccess data[] as if it had been allocated * as data[ARRAYarray_SIZEsize] */ for (i = 0; i < ARRAYarray_SIZEsize; i++) { structP->data[i] = i1; } |
Wiki Markup |
---|
The problem with this code is that the only member that is guaranteed to be valid, by strict C99 definition, is {{structP->data\[0\]}}. Consequently, for all {{i > 0}}, the results of the assignment are undefined. |
...
Code Block | ||
---|---|---|
| ||
struct flexArrayStruct{ int num; int data[]; }; /* ... */ size_t array_size; size_t i; /* initialize array_size */ /* Space is allocated for the struct */ struct flexArrayStruct *structP = (struct flexArrayStruct *) malloc(sizeof(struct flexArrayStruct) + sizeof(int) * ARRAYarray_SIZEsize); if (structP == NULL) { /* handle malloc failure */ } structP->num = SOME_NUMBER0; /* Access data[] as if it had been allocated * as data[ARRAYarray_SIZEsize] */ for (i = 0; i < ARRAYarray_SIZEsize; i++) { structP->data[i] = i1; } |
Wiki Markup |
---|
This compliant solution allows the structure to be treated as if it had declared the member {{data\[\]}} to be {{data\[ARRAYarray_SIZEsize\]}} in a manner that conforms to the C99 standard. |
...