Are arrays a variable by default length in C?

I tried to create a linear list based on an array, then I compiled this:

char size = 0; char testarray[10]; int main() { add('a'); add('b'); add('c'); add('d'); add('e'); add('f'); add('g'); add('h'); add('i'); add('j'); add('k'); add('l'); add('m'); add('n'); add('o'); print(); return 0; } void add(char newchar) { testarray[++size] = newchar; } void print() { char i = 0; for (i = 0; i <= size; i++) { printf("%c ", testarray[i]); } } 

And compiled it with gcc arraytest.c , but the array works fine. Does this mean that arrays are of variable length by default? I thought it was a C99 feature.

It was compiled under both Gentoo ( gcc version 4.5.3 (Gentoo 4.5.3-r2 p1.1, pie-0.4.7 ) and Ubuntu ( gcc version 4.6.1 (Ubuntu/Linaro 4.6.1-9ubuntu3 ) .

Oh, and isn't that dangerous?

+4
source share
4 answers

As long as you are within the allocated range for your application, you can use pointers / address wherever you want. keep going far enough and you either destroy your program or fall into the edge of your allocated memory and get some kind of protection. Checking the execution time is expensive, but in any case does not want to.

replace two variables

 char testarray[10]; char size = 0; 

and see what happens when you run it ...

And then do the following:

 char size = 0; char testarray[10]; char stuff[10]; 

before you start adding things to testarray, initialize the material, and then after doing your work, print out the stuff [] array. You should see an overflow. In C, the correct rule is to first transfer variables without an array to the assignment list, and the array or arrays last, you have a better chance of debugging.

+4
source

No, they are not variable sizes. You just write the end of the array and knock down another memory. There are no checks to make this obvious.

+7
source

Not


Think of C as the world, which is the most amazing assembly language, and it is portable too. This is completely unlike languages ​​designed to provide in-memory security. (That would be most of the others).

One way to answer such questions (that is, “what does C really do”) is to compile with cc -S ... and verify the generated assembly code. Even if you are not familiar with machine language, you can probably say that it does not call or does not check the range of indices.

C can never do this, because it happens because x[i] is defined as *(x + i) , so it really is really a "high-level assembly language," as they say.

+5
source

As Vaugh said, you're just “happy” * in that the memory behind the array is writable. There is a possibility of segmentation failure. In fact, if you change the program a bit so that the array is on the stack, and then run it through valgrind, it will fill you with the number of warnings.

* "Lucky" is that the program did not work. Unlucky in that ... it will be later.

+2
source

Source: https://habr.com/ru/post/1403190/


All Articles