C global unsized array?

arrays, c, linked-list

Solution

int array[];

Is technically known as an array with incomplete type. Simply put it is equivalent to:

int array[1];

This is not good simply because:

- It produces an Undefined behavior. The primary use of array with incomplete type is in Struct Hack. Note that incomplete array types where standardized in C99 and they are illegal before.

Problem

We had a school project, any information system using C. To keep a dynamic-sized list of student records, I went for a linked list data structure. This morning my friend let me see his system. I was surprised with his list of records: ``` #include <stdio.h> /* and the rest of the includes */ /* global unsized array */ int array[]; int main() { int n; for (n=0; n < 5; n ++) { array[n] = n; } for (n=0; n < 5; n ++) { printf("array[%d] = %d\n", n, array[n]); } return 0; } ``` As with the code, he declared an unsized array that is global (in the bss segment) to the whole program. He was able to add new entries to the array by overwriting subsequent blocks of memory with a value other than zero so that he can traverse the array thusly: ``` for (n=0; array[n]; n++) { /* do something */ } ``` He used (I also tested it with) Turbo C v1. I tried it in linux and it also works. As I never encountered this technique before, I am presuming there is a problem with it. So, yeah, I wanna know why this is a bad idea and why prefer this over a linked list.

Original source