Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sscanf not work properly with a bool type

Tags:

c++

c

boolean

scanf

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.

like image 628
Salgar Avatar asked Jul 14 '11 12:07

Salgar


People also ask

Why Scanf function is not working?

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).

Does Sscanf move pointer?

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.


2 Answers

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.

like image 153
Ernest Friedman-Hill Avatar answered Oct 15 '22 22:10

Ernest Friedman-Hill


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.

like image 44
Mike Seymour Avatar answered Oct 15 '22 22:10

Mike Seymour