Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this assignment break my program?

Tags:

c

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.

like image 213
red888 Avatar asked Jun 22 '26 14:06

red888


1 Answers

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.

like image 188
Sergey Kalinichenko Avatar answered Jun 24 '26 04:06

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!