I am learning C and I'm not sure how to phrase this, but why does uncommenting line 11 in the following code break this program?
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("argc: %d\n", argc);
char *states[] = {};
int i = 0;
while(i < argc) {
printf("arg %d: %s\n", i, argv[i]);
//states[i] = "test";
i++;
}
return 0;
}
When I uncomment this line and run the program I get this:
greggery@Lubu:~/code$ ./myprog aaa bbb ccc
argc: 4
arg 0: ./lc
arg 1: aaa
Why is states[i] = "test"; breaking the while loop? When I comment it out I see all the arguments printed.
It breaks because the array states is empty. Make it the size of argc (that's allowed in C99) to fix the problem:
char *states[argc];
The reason for this is as follows: char *states[] = {}; makes an array of zero elements, so any dereference states[i] is undefined behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With