Why does scanf("%s") behave strangely with char*?

Viewed 98

I was trying to solve this problem

When i create a char * and pass it into scanf:

char* input = "";
scanf("%s", input);

It behaves weirdly.
However, when i change the definition and initalize 1000 chars to \0:

char input[1000] = { '\0' };

It behaves properly. Why is it that way?

2 Answers

I'm guessing you're seeing a segmentation fault. When you declare char* input = "";, you're causing input to be a pointer directed at a string literal. String literals are stored in a read-only section of memory. Therefore, trying to overwrite the data with scanf is an invalid use of memory.

However, when you declare char input[1000];, you've now got an array on the stack, which is a section of memory which can be written to. That's why that code works.

First question is what does this declare?

char* input = "";

That's a single byte in a non-mutable (read-only) area of memory. If you write anything to it, that's undefined behaviour, or something more colloquially described as weird behaviour.

When you re-write it correctly you get a 1000 character buffer and you can read to it without undefined behaviour, provided your input is < 1000 characters.

Related