I was trying to make an array-based linear list, 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 just fine. Does that mean arrays are variable-length by default? I thought it was a C99-only 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 this a bit dangerous?
So long as you are within your allocated range for your application you can use pointers/address wherever you want. keep going far enough and you either trash your program or hit the edge of your allocated memory and get a protection fault of some sort. Runtime checking is expensive, wouldnt want to have that anyway.
swap your two variables
and see what happens when you run it…
And then do this:
before you start adding things to testarray, initialize stuff, then after doing your thing print out the stuff[] array. You should see your overflow. In C it is a good rule to put your non-array variables first in the assignment list and the array or arrays last, you have a better chance at debugging.