strtol expects a NUL terminated string. Your array declaration creates a 7 character array and populates all 7 positions with non-NUL data. Thus, strtol actually continues to look up the stack (or through memory) until it finds a terminating character.
You have a number of options for declaring a char array and initializing it correctly. If it is a read-only array, I prefer:
char xs[] = "0001010";
which will create an array large enough to hold the string literal (including its terminating NUL).
The advantage of either my approach, or the final one above, is that you don't need to count the characters, and the compiler will adjust if you change the string.
In the first example above, \0 is the escape sequence representing the ASCII NUL character. It is preferable to a plain 0 because (a) it has the correct type (char) for inclusion in a string literal, and (b) most syntax-aware editors will highlight it, as a NUL in the middle of a literal can have surprising results. For example
strtol
expects a NUL terminated string. Your array declaration creates a 7 character array and populates all 7 positions with non-NUL data. Thus,strtol
actually continues to look up the stack (or through memory) until it finds a terminating character.You have a number of options for declaring a
char
array and initializing it correctly. If it is a read-only array, I prefer:which will create an array large enough to hold the string literal (including its terminating NUL).
Other options are shown in the comments above
The advantage of either my approach, or the final one above, is that you don't need to count the characters, and the compiler will adjust if you change the string.
In the first example above,
\0
is the escape sequence representing the ASCII NUL character. It is preferable to a plain0
because (a) it has the correct type (char
) for inclusion in a string literal, and (b) most syntax-aware editors will highlight it, as a NUL in the middle of a literal can have surprising results. For example