The output of this code:
const char *buff = "*_2D 1";
char field[10];
int flag;
sscanf(buff, "%s %d", field, &flag);
printf("field:%s flag:%i\n", field, flag);
is field:*_2D flag:1
However by changing the int
to bool
results in strange behaviour:
const char *buff = "*_2D 1";
char field[10];
bool flag;
sscanf(buff, "%s %d", field, &flag);
printf("field:%s flag:%i\n", field, flag);
The output is field: flag:1
Can anyone explain what is happening here? I would've thought the bool would be interpreted as an int, which it appears to be, but the rest of the string disappears.
This happens because every scanf() leaves a newline character in a buffer that is read by the next scanf. How to Solve the Above Problem? We can make scanf() to read a new line by using an extra \n, i.e., scanf(“%d\n”, &x) . In fact scanf(“%d “, &x) also works (Note the extra space).
The same string pointer is passed each time you call sscanf . If it were to "move" the input, it would have to move all the bytes of the string each time which would be slow for long strings. Furthermore, it would be moving the bytes that weren't scanned.
Imagine if bool
is only one byte, rather than the four (or even eight) that an int
uses. Then telling sscanf
that &flag
is a pointer to an int
will end up overwriting either three or seven bytes elsewhere on the stack -- which could be right on top of your field
variable. That space would be filled with 0 bytes, effectively terminating your string.
bool
is a separate type to int
, and is likely to be a single byte (which on most common platforms is smaller than int
).
sscanf
is not type-safe; you are telling it (with the %d
conversion specifier) that you are providing a pointer to an int
, and so it assumes that it is safe to write an int
there. If the actual type is smaller, then you'll get undefined behaviour; most likely, either other local variables will be overwritten, or the stack frame will be corrupted. In this case, it looks like it is overwriting the beginning of field
with the zero-valued bytes of the integer value 1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With