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?

4
  • 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. Commented Jul 24, 2022 at 17:35
  • 1
    With any input longer than 3 chars this is undefined behaviour, global variable or not. Commented Jul 24, 2022 at 17:37
  • Also, please tag the actual language you're using. C and C++ are different languages. Commented Jul 24, 2022 at 17:37
  • Questions seeking debugging help should generally provide a minimal reproducible example of the problem, which includes all #include directives as well as the exact input required to reproduce the problem. Commented Jul 24, 2022 at 17:37

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

ohhh that makes sense, I'm used to typescript and python so bare with my newb c skills

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.