red888
red888

Reputation: 31610

Why does this assignment break my program?

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.

Upvotes: 3

Views: 166

Answers (2)

Tyler McAtee
Tyler McAtee

Reputation: 300

You need to allocate memory for the character array. If argc is the number of characters you want to store:

char *states[argc];

Works. Or if you want to dynamically expand it you can use the heap, keep a counter variable and add the following in your loop:

states = (char *) realloc(sizeStates + sizeof(char));
sizeStates++;

To make room for the next character before you assign it.

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726839

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.

Upvotes: 9

Related Questions