C global unsized array?

We had a school project, any information system using C. To save a list of student records of dynamic size, I went to the structure of linked lists. This morning my friend let me see his system. I was surprised by his list of entries:

#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 code, it declares an unserialized array that is global (in the bss segment) for the entire program. He was able to add new entries to the array, overwriting the following blocks of memory with a non-zero value so that he could move around the array:

 for (n=0; array[n]; n++) { /* do something */ } 

He used (I also tested it) with Turbo C v1. I tried this on linux and it also works.

As I have never seen this method before, I assume that there is a problem with it. So yes, I want to know why this is a bad idea and why they prefer it on a linked list.

+6
source share
3 answers
 int array[]; 

Technically known as an array with an incomplete type . Simply put, this is equivalent to:

 int array[1]; 

This is not good because:

  • It creates Undefined behavior. The main use of an incomplete array is Struct Hack . Please note that incomplete types of arrays are standardized on C99, and they are illegal before that.
+6
source

This behavior is undefined . You write unallocated memory (outside the array). To compile this, the compiler selects at least one element, and then you write after it. Try a much larger range of numbers. For example, if I run your code on Linux, it works, but if I change the cycle to 50,000, it will work.

EDIT . The code may work for small values ​​of n , but for large values ​​it will fail. To demonstrate this, I wrote your code and tested it for n = 1000 .

Here is a link to CODEPAD , and you can see that a segmentation error occurred for n = 1000 a.

Given the same code with the same compiler, it works for n = 10, see this CODEPAD link. Thus, this is called undefined behavior .

+3
source

If you use linked lists, you can check if the memory is allocated correctly.

 int *ptr; ptr = (int *)malloc(sizeof(int)) if(ptr==NULL) { printf("No Memory!!!"); } 

But with your code, the program simply crashes if it is tested with an array that has a large border.

+1
source

All Articles