0

So, I have some code like:

char* t2 = strtok(NULL, " \t\n,");
char regN[3];
strcpy(regN, t2);
Register* rt = getRegister(regN);

I checked several times the value of regN by printing is $t0 but the function returns NULL. However when I tried getRegister("$t0") it returns the correct value. The only reason I can think for this is if strtok() returns something other than the predicted value. Yes, the next token is $t0. I checked this as well. Any suggestions or ideas what is going wrong here?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • How do you know the returned token will be 2-element long only? – Sourav Ghosh Nov 22 '19 at 07:14
  • 1
    What exactly do you expect `char* t2 = strtok(NULL, " \t\n,");` to return? Please make an [mre]. – Yunnosch Nov 22 '19 at 07:29
  • The second and third lines are of no value, and in fact (as the next comment explains) they may be harmful. You can simply pass `t2` to `getRegister`. – user3386109 Nov 22 '19 at 07:34
  • 3
    If I understand your explanation correctly, and the next token is `"$t0"`, then that's too long for `regN` (which can only hold a null-terminated string of max. 2 characters long, not 3). Hence, [undefined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) ... – Sander De Dycker Nov 22 '19 at 07:36
  • 1
    What is `getRegister()`? Did you call `strtok()` before? On what input string? What do you mean by `getRegister("$t0")`? There is no `strcmp()` in the shown code, yet your question is about it. So, please, provide an MRE. – Yunnosch Nov 22 '19 at 07:36

1 Answers1

2

Three char long string must be stored in the 4 char array as it also needs the space for terminating zero. Your array is 3 chars long, so you have the Undefined Behaviour here

0___________
  • 60,014
  • 4
  • 34
  • 74