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.
The
sscanf
function failed becausebool
is not anint
but achar
Try this one:
It'll give you the same error.
It could be because
sizeof(bool)
is sometimes1
? So, I don't know much C++, but in C that would be undefined behavior.Imagine if
bool
is only one byte, rather than the four (or even eight) that anint
uses. Then tellingsscanf
that&flag
is a pointer to anint
will end up overwriting either three or seven bytes elsewhere on the stack -- which could be right on top of yourfield
variable. That space would be filled with 0 bytes, effectively terminating your string.If you are using C++ (which appears to be the case from your comments), why not use C++ streams instead of the C-style
scanf
approach ?According to the spec for sscanf, the description of %d is:
Also from the same spec,
Since sizeof(bool) < sizeof(int), you are in the dreaded Undefined Behavior zone, and anything can happen.
bool
is a separate type toint
, and is likely to be a single byte (which on most common platforms is smaller thanint
).sscanf
is not type-safe; you are telling it (with the%d
conversion specifier) that you are providing a pointer to anint
, and so it assumes that it is safe to write anint
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 offield
with the zero-valued bytes of the integer value1
.