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?
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?
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.