I would like to indicate that the source code of the buggy is:
bool is_int(char const* s) { int n; int i; return sscanf(s, "%d %n", &i, &n) == 1 && !s[n]; }
I will explain why. And I will interpret the sscanf format string.
Firstly, buggy:
Given input "1", which is an integer, sscanf will store 1 in i. Then, since there is no space after the space, sscanf will not touch n. And n is not initialized. Since sscanf sets me to 1, the value returned by sscanf will be 1, which means 1 scanned field. Since sscanf returns 1, part of the expression
sscanf(s, "%d %n", &i, &n) == 1
will be true. Therefore, the other part of the && expression will be executed. And s [n] will gain access to some random place in memory, because n is not initialized.
Interpretation of the format:
"%d %n"
Trying to scan a number, which can be a decimal or an integer or a scientific notation number. A number is an integer followed by at least one space. Empty space would be space, \ n, \ t and some other non-printable characters. Only if followed by a space will it set n to the number of characters scanned to this point, including a space.
This code may be what is intended:
static bool is_int(char const* s) { int i; int fld; return (fld = sscanf(s, "%i", &i)) == 1; } int main(int argc, char * argv[]) { bool ans = false; ans = is_int("1"); ans = is_int("m"); return 0; }
This code is based on, if s is an integer, then sscanf will scan it, and fld will be exactly one. If s is not an integer, then fld will be zero or -1. Zero, if there is something else, like a word; and -1 if there is nothing but an empty string.