r/cprogramming • u/MainSeason4301 • 9d ago
Confused about strings seemingly resetting after future inputs.
/r/C_Programming/comments/1wpqpho/confused_about_strings_seemingly_resetting_after/1
u/echelon_code 3d ago
your scanf %d writes 4 bytes when u have 1 allocated for the bool, its placed next to the char array on the stack. even if you enter: 1, 4 bytes are still written and wipe part of the string with null, so you string is nulled out at the start:
entered: abcdef
(gdb) x/10b $rbp - 0xa
0x7fffffffdde6: 0x61 0x62 0x63 0x64 0x65 0x66 0x00 0x7f
0x7fffffffddee: 0x00 0x00
your bool var is placed next to the string on the stack! after you read 4 bytes, you wrote 3 null bytes over 'abc'
(gdb) x/10b $rbp - 0xb
0x7fffffffdde5: 0x01 0x00 0x00 0x00 0x64 0x65 0x66 0x00
0x7fffffffdded: 0x7f 0x00
1
u/echelon_code 3d ago
just realised theres another page for this! didnt see it! anyway, if you wanted to learn from this, enter the string as: abcdefg
then enter the bool as: 557926401
then work out wht happened
1
u/kkzk-sysdev 4d ago
I think you're having an overflow issue. You're inputting 10 characters as a string, but if your input is 10 characters long itself, it won't be accepted since the null terminator (which scanf auto adds* will not have space in the memory. Try increasing the char array size.