kennedyl
kennedyl

Reputation: 181

atoi() returning strange value

I'm getting some very strange behavior out of the atoi command. I am trying to find 2 values out of a range with the format [1:2] The string being created is done with a dynamic string allocating macro (if Sasprintf throws you) It will be read in from a file at projects end, however. Anyway, I seem to be parsing my string correctly, given the correct values of token and token2. I'm confused, however, why calling atoi on token2 would give me a gibberish answer. Also, I found out in the midst of this that strtok is deprecated, I just haven't bothered switching it yet, until I solve this bug.

char *token;
char *token2;

int lsb = 0;
int msb = 0;    
char *str = NULL;

Sasprintf(str,"[4:0]");

token = strtok(str,"[");
if(token != NULL)
{
    token = strtok(token,":");
    msb = atoi(token);
    printf("%d\n", msb);
    token2 = strtok(NULL,"]");
    puts(token2);

    lsb = atoi(token2);
    printf("%d\n",token2);
}

OUTPUT

4

0

19853443

Upvotes: 0

Views: 453

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

I think, you need to change

  printf("%d\n",token2);

to

  printf("%d\n",lsb);

token2 is a char * and you cannot print that using %d. Invokes undefined behavior

That said, always check the return value of strtok() against NULL. Also, strtod() is a better alternative to atoi().

Upvotes: 2

ouah
ouah

Reputation: 145919

    printf("%d\n",token2);

This is not how you print a string, use:

    printf("%s\n",token2);

or

    printf("%d\n", lsb);

to print the result of your conversion.

Upvotes: 1

Related Questions