r/C_Programming • u/MainSeason4301 • Sep 25 '26
Question Confused about strings seemingly resetting after future inputs.
Hello! Sorry that this is such a basic question but I'm genuinely confused about this weird problem I had with scanf and strings. I've only just begun learning C and have been following a beginner's guide over on github.
Below I've written what my code was while I was having issues. The issue was that when the time came to print the values it would return the boolean value just fine, but the string would be blank. I added some extra prints in there to check if it was taking the input at all and it was! It was only after the boolean value was taken and stored that user_input began to return blank. I then tried googling for a very long time and couldn't find any solution (other than the odd tidbit about scanf not being great for strings), so in an act of desperation I tried changing char user_input[10] to static char user_input[10] and then suddenly it worked!
Somewhere along the line it must be overwriting or erasing the data stored in the array but I just don't understand where or why? Apologies again that this is such a basic question but I'd just really like to understand this a bit better, especially as no solution I could find suggested anything remotely like this.
#include <stdio.h>
#include <stdbool.h>
int main() {
char user_input[10];
bool tof;
printf("Enter a string: ");
scanf("%s", user_input);
printf("Enter a boolean value: ");
scanf("%d", &tof);
printf("String: %s\n", user_input);
printf("Boolean value: %d\n", tof);
return 0;
}
26
u/dmills_00 Sep 25 '26 edited Sep 25 '26
Is %d the correct format character for a bool? This is undefined behaviour so anything could happen, but probably what is happening is this:
The layout on the stack has your bool at a lower address then the array, and "%d" tells scanf to expect an integer which is likely 32 bits, a bool is probably 8 bits. When scanf writes the integer thru the pointer the upper bytes of the integer are overwriting the first few bytes of the array, boom.
1
u/MainSeason4301 Sep 25 '26
Thank you all! Apologies again if this seems a particularly dumb question with obvious answers and solutions. I don't yet have any clue what I'm doing. You've all pointed me in some very helpful directions though :)
5
u/ferrybig Sep 25 '26
Your stack is allocated as:
Your first scan writes to user_input, with the length depending on the input. You are not passing the max length here, so there is change it writes beyond its boundary, resulting in potential UB
You second scan searches for %d, this writes 4 bytes to the memory address pointed by your spec. tof only fits 1 byte, so this results in undefined behaviour, overwriting user_input. Depending if the LE or BE is used, the first 3 bytes of user_input get overwritten with either 0x000000 or 0x000001. Both result in the string code seeing it as an empty string
3
u/siliconlore Sep 25 '26
Be super careful with that implementation -- you have a possible buffer overflow if you type in more than 10 characters. You need to specify a size limit.
When you made your array static, that would have pre-initialized the buffer so that's related somehow.
2
u/StarJaded Sep 25 '26
scanf is generally an unsafe function to use as it can overwrite memory in unexpected ways.
My guess is that the scanf("%d", &tof); line is overwriting the space assigned to tof, and also writing over the start of char user_input[10];
When you changed it to static that results in user_input[10] being stored in a physically different bit of memory that isn't adjacent to tof.
Have a google of unsafe scanf.
You also have the problem that scanf("%d", &tof); in that the format specifier say that you are expecting an integer, but you have supplied a pointer to a bool. The space a bool occupies can vary from that of an integer depending on the C compiler.
2
u/DawnOnTheEdge Sep 25 '26
By the way, never, absolutely never ever, read into a buffer without bounds-checking! If this is just an assignment you’re doing to learn C, learn good habits.
2
u/SmokeMuch7356 Sep 25 '26
%dexpects anint *argument and will writesizeof (int)bytes to that target. Abool *is not anint *, andsizeof (bool)is most likely less thansizeof (int), so what's likely happening is thatscanfis overwriting the first few bytes ofuser_inputwith zeroes.I say likely because the behavior is undefined; the compiler is not required to handle the situation in any particular way.
A quick, unsafe fix would be to use the
hhlength modifier:This will write
sizeof (char)bytes to the target; however, the behavior is still undefined because the types still don't match.A safer alternative is to read a string, character, or integer input and map that to your boolean:
If that seems like a lot of work to read one stinking Boolean value - you're right, it is. Welcome to C.
scanfis not an appropriate tool for interactive user input; it requires significant bulletproofing to guard against bad or unexpected input, otherwise it will fail in surprising and exciting ways.Speaking of which, never use
%sor%[without an explicit field width:This will stop reading the input stream after 9 characters, which will a) ensure that
user_inputis properly terminated, and b) prevent a buffer overflow if the input is more than 10 characters long.Unfortunately, field widths must be hardcoded in the format string; you can't use a runtime argument like you can with
printf.At the end of the day,
fgetsis the better option for reading text input:1
u/detroitmatt Sep 25 '26
What inputs are you giving it? If you put the working version in at https://godbolt.org/ and compare it to the broken version, what is the difference in the assembly?
1
u/Layzy37 Sep 25 '26
You should never ever use scanf. It is a deprecated and unsafe function. You should use fgets on stdout instead (since it restricts the number of bytes read) and then convert it to integer using atoi if you only want base 10 numbers and strtol/strtoll else
1
u/FitMatch7966 Sep 26 '26
bool is smaller than an int. So those extra bytes it needs to write a full integer just happen to be the start of your string, overwriting the beginning of your char[] with zeros
1
u/JGhostThing Sep 28 '26
Any time you input a string in scanf(), please put the proper length of the field so you don't cause problems. For example, any length of string could be input, even more than ten. This might blow up the program, because there is no memory there.
1
u/P1nkUnicorn7 Sep 25 '26
My guess would be that you need to add the string escape character \0 as the last character.
0
u/AnxiousPackage Sep 25 '26
I haven't used stdbool.h, but I assume you are going either a 1 or 0, yes? (Based on the scant having %d).
Also, are you missing a & before your string name in scanf? May not matter because of arrays decaying to pointer, so not sure.
But you should definitely search how to limit string length for scanf so you don't overflow the buffer. (And remember to leave one char for null terminator)
0
u/[deleted] Sep 25 '26
[deleted] — view deleted comment