1

Why this code appear segment fault?

int main(int argc,char *argv[]){
    int *role;
    sscanf(argv[1],"%d",role);

    return 0;
}

...but the second one is ok:

int main(int argc,char *argv[]){
    int *role = new int;
    sscanf(argv[1],"%d",role);

    return 0;
}
genpfault
  • 51,148
  • 11
  • 85
  • 139
zhou
  • 21
  • 1
  • 2
    Because in first case `role` doesn't point to anything. In other words, it is uninitialized and you're using it. So the program has undefined behavior. – Jason Mar 30 '23 at 13:33
  • 1
    You never put a value in "role", it contains a garbage address. Then you tell sscanf to write the decoded `int` to the garbage address. You mean `int role; sscanf(argv[1], "%d", &role);` – doug65536 Mar 30 '23 at 13:34

1 Answers1

2

In the first one, role is an uninitialized pointer: it's not pointing to any memory that you "own". So the sscanf function is writing the result into that area of memory, and (rightly) failing.

Steven Frew
  • 214
  • 2
  • 9
  • In the first exapmple, role is not assigned with any value (only DECLARED), so no space is allocated in your memory. Maybe try using malloc() (https://cplusplus.com/reference/cstdlib/malloc/) to pre-allocate memory or you just use the second example. – Animalz Mar 30 '23 at 13:39