Why strtol returns wrong value?

1.3k Views Asked by At
char xs[7] = {'0','0','0','1','0','1','0'};
long ss = strtol(xs, NULL, 2);

after 2nd line ss is 2147483647, any ideas? following code is in the loop (outside it works fine)

1

There are 1 best solutions below

3
On

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

Other options are shown in the comments above

char xs[7+1] = "0001010\0";
char xs[7+1] = {'0','0','0','1','0','1','0',0};
char xs[ ] = {'0','0','0','1','0','1','0',0};

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

   strlen("abc\0def") == 3