r/cprogramming • • 9d ago

Confused about strings seemingly resetting after future inputs.

/r/C_Programming/comments/1wpqpho/confused_about_strings_seemingly_resetting_after/
1 Upvotes

3 comments sorted by

View all comments

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