Segmentation Fault when trying to populate array of strings in C

Viewed 41
    
int main() {
    const char* text = "the quick brown fox jumps";
    int* argc = 0;
    char *argv[] = {};
    printf("%d", parse_command(text, argc, argv));
}

int parse_command(const char *inp, int *argc, char *argv[]) {
    int offset = 0;
    int count = 0;

    int i = 0;
    bool bool1 = true;
    while (*(inp + offset) != '\0') {
        if (inp[i] == ' ')
            bool1 = true;

        if (bool1 && inp[i] != ' ') {
            bool1 = false;
            argv[i] = &inp[i];
            ++count;
        }
        ++offset;
        i++;
    }
    *argc = count;
    return count;
}

I am trying to split the character array inp into words, and return the number of words. What is considered a word is: a sequence of non-blank characters ending in one or more blank spaces. I want argc to be set to the number of words (which I think works fine), and argv[0] should point to the first character of the first word, argv[1] to the first character of the second word, and so on.

I keep getting segmentation fault error. Is this because char* argv[] is empty when initialized? If so, how can I initialize it to a specific length?

1 Answers

When you declare int *argc = 0 you are creating a pointer, and setting its value to 0.

Then dereferencing this pointer is invalid as it is a null pointer, which results in a segfault.

What you can do is create an integer (int argc = 0) and pass it by reference to the function (&argc).

Related