Home > front end >  Reading argv[1] gives Segmentation Fault 11 although argc indicates there's two parameters
Reading argv[1] gives Segmentation Fault 11 although argc indicates there's two parameters

Time:10-29

I stumbled upon an issue whereby if I want to read input arguments not inside the main method but inside another method into which argv is passed by reference I'm getting Segmentation Fault 11 for reading argument from argv[1] that succeeded in the main method.

I understand why segmentation fault happens - it's when program tries read outside the memory allocated for it. But here it seems to me I'm doing everything right - reading argv[1] is valid in main method. Also reading argv[0] is valid in the handleInput method but for reading argv[1] inside handleInput method I get Segmentation fault: 11. argc also indicates there's two parameters but I can only read the first one (the executable filename).

segfault

#include <stdio.h>

void handleInput(int *argc, char ***argv) {
    printf("%d\n", *argc);
    printf("%s\n", *argv[0]);
    printf("%s\n", *argv[1]);
    printf("\n");
}

int main(int argc, char **argv) {
    printf("%d\n", argc);
    printf("%s\n", argv[0]);
    printf("%s\n", argv[1]);
    printf("\n");

    handleInput(&argc, &argv);

    return 0;
}

$ ./segfault parameter

2
./segfault
parameter

2
./segfault
Segmentation fault: 11

I'm using clang compiler on MacOS

$ clang -v
Apple clang version 14.0.0 (clang-1400.0.29.102)
Target: arm64-apple-darwin22.1.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Why can't I read argv[1] inside handleInput method? What am I doing wrong?

CodePudding user response:

There's no need to pass pointers to argc and argv, since you're not planning on changing them. Passing by value is fine! Just use them as-is. This should work:

#include <stdio.h>

void handleInput(int argc, char *argv[]) {
    printf("%d\n", argc);
    printf("%s\n", argv[0]);
    printf("%s\n", argv[1]);
    printf("\n");
}

int main(int argc, char *argv[]) {
    printf("%d\n", argc);
    printf("%s\n", argv[0]);
    printf("%s\n", argv[1]);
    printf("\n");

    handleInput(argc, argv);

    return 0;
}

I replaced the char **argv with char *argv[] to make it more obvious it is an array of strings.

  • Related