0
int main(){
char x[] = "123";
srand(time(NULL));
scanf("%s", x);
printf("%s\n", x);

// run();

return 0;
}

But when I make x a global variable it works just fine. Is there any reason behind this?

Jason
  • 36,170
  • 5
  • 26
  • 60
Markis
  • 3
  • 1
  • 4
    `scanf("%s", x);` -- What is the input? If it's more than 3 characters, that is a buffer overrun, regardless of whether it is global or local. – PaulMcKenzie Jul 24 '22 at 17:35
  • 1
    With any input longer than 3 chars this is undefined behaviour, global variable or not. – fabian Jul 24 '22 at 17:37
  • Also, please tag the actual language you're using. C and C++ are different languages. – PaulMcKenzie Jul 24 '22 at 17:37
  • Questions seeking debugging help should generally provide a [mre] of the problem, which includes all `#include` directives as well as the exact input required to reproduce the problem. – Andreas Wenzel Jul 24 '22 at 17:37

1 Answers1

3

If you're entering in more than 3 characters, you're writing past the end of the array. Doing so triggers undefined behavior.

With undefined behavior, there are no guarantees regarding what your program will do. It may crash, it may output strange results, or it may appear to work properly.

As for what's happening in practice, local variables reside on the stack. So if you write past the bounds of a stack variable, you could end up overwriting the function's return pointer to its caller or over special sentinel values that are designed to detect such a case.

Global variables on the other hand reside in a data section, not the stack, so it's unlikely that stack objects could be overwritten. It's still possible to overwrite other objects however.

dbush
  • 205,898
  • 23
  • 218
  • 273