0

If you have a string as below str="insert 111,name,123456789" when you pass it to strtok and try to print the values, they are output in reverse. For example:

char* token=strtok(str," ");
printf("%s %s %s %s\n",token,strtok(NULL,","),strtok(NULL,","),strtok(NULL,","));
output: insert 1234567 name 1111

instead of:insert 111 name 123456789 Why is this happening? How can this be fixed?

henrykorir
  • 107
  • 1
  • 12
  • 3
    The argument evaluation order is not defined. Don't use code with side-effects (like calling `strtok`) in arguments. – Some programmer dude May 27 '17 at 19:40
  • 1
    Perhaps you are experiencing an *Indeterminently Sequenced* result because of the *sequence point* error, as there is no guarantee on the order of parameter evaluations. **C11 Standard Sect. 6.5.2.2 (10)** – David C. Rankin May 27 '17 at 19:41
  • How can it be fixed? by using the idiomatic `while(token != NULL)` loop. Your version is terrible also, because if one of the calls to `strtok` should return `NULL` you should not call it again. Never rely on input data being what you think it should be. – Weather Vane May 27 '17 at 19:49
  • ... and you will be passing `NULL` for the `%s` format. – Weather Vane May 27 '17 at 19:55

1 Answers1

1

parameters are pushed to the stack in the Calling Convention order, which in your case, reverse... therefore parameter 5 is first to evaluate and pushed in the stack, then 4,3,2 and the format string.

as many comments before suggested, your call style is very discouraged, and should be avoided.

Tomer W
  • 3,395
  • 2
  • 29
  • 44
  • And with respect to `x86_64` parameters passed by register -- how does that work out? (you should distinguish between integer arguments and all others) – David C. Rankin May 27 '17 at 19:49