Two Things that Drove Me Nuts Today

One: strtok(). 

See, the thing about strtok() (we're talking c here) is that you can't call this function when it's being used elsewhere. Say you have a function:

void DoSomething(void) {
      char MyString[] = "Hello all you people";
      char seps[] " ";
      char *token;
      // get the first token in a string:
      token = strtok(MyString,seps);
      printf("token: %s\n",token);
     while (token!=NULL) {
           token = strtok(NULL,seps);
           printf("token: %s\n",token);
      }
}

All well and good. But, say you're in another module of code and want to use strtok() again,  called from a function within your DoSomething() function:


void DoSomething(void) {
      char MyString[] = "Hello all you people";
      char seps[] " ";
      char *token;
      // get the first token in a string:
      token = strtok(MyString,seps);
      printf("token: %s\n",token);

     while (token!=NULL) {
           token = strtok(NULL,seps);
          GoGetMeMoreTokens(void);
           printf("token: %s\n",token);
      }
}

void GoGetMeMoreTokens(void) {

      char MyString[] = "Welcome to my wormhole!";
      char seps[] " ";
      char *token;
      // get the first token in a string:
      token = strtok(MyString,seps);
      printf("token: %s\n",token);

     while (token!=NULL) {
           token = strtok(NULL,seps);
           printf("token: %s\n",token);       }

}

The nested call to strtok() clobbers the pointer to the current token in the outer function, and eventually, boom - memory leak and probably (on Windows) an access violation error.

I've known this for years. And yet.... well, sometimes your brain just goes to sleep....

Two: spawn()

Windows is very misleading with regard to informing you of what is wrong with a spawn() call. You might, for example, use spawnlp() to run a process:

status = _spawnlp( _P_WAIT, cmd, arg1, arg2, NULL);

Simple enough, but if any of the arguments (cmd, arg1, or arg2) are not acceptable, status will be -1 and errno set to EINVAL, which documentation states is an invalid mode. No it ain't, either. Things that can cause EINVAL include quotes inside an argument (cmd, arg1, arg2, etc.) and multiple NULL arguments.

That was extremely annoying to discover....

Comments

Popular posts from this blog

Zombies? What Zombies?