c - Why does this assignment break my program? -
i learning c , i'm not sure how phrase this, why uncommenting line 11 in following code break program?
#include <stdio.h> int main(int argc, char *argv[]) { printf("argc: %d\n", argc); char *states[] = {}; int = 0; while(i < argc) { printf("arg %d: %s\n", i, argv[i]); //states[i] = "test"; i++; } return 0; }
when uncomment line , run program this:
greggery@lubu:~/code$ ./myprog aaa bbb ccc argc: 4 arg 0: ./lc arg 1: aaa
why states[i] = "test";
breaking while
loop? when comment out see arguments printed.
it breaks because array states
empty. make size of argc
(that's allowed in c99) fix problem:
char *states[argc];
the reason follows: char *states[] = {};
makes array of 0 elements, dereference states[i]
undefined behavior.
Comments
Post a Comment