Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are arrays variable-length by default on C?

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?

like image 916
user1002327 Avatar asked Dec 01 '22 23:12

user1002327


1 Answers

No, they aren't variable size. You are just writing past the end of the array and clobbering some other memory. There are just no checks to make that obvious.

like image 156
Vaughn Cato Avatar answered Dec 14 '22 07:12

Vaughn Cato