Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #16762
    gryphacus
    Participant

    I am trying to test functionality of strtok() on a Rocketscream V3 (without radio), as I ran out of memory to develop on my Nano. This is a basic example from the internet involving tokenizing the string and reporting the tokenized entries via SerialUSB.

    #include <string.h>
    
    void setup() {
      char *token;
      char *mystring = "apples,pears,bananas";
    
      SerialUSB.begin(9600);
      while (!SerialUSB) { }
    
      SerialUSB.print("Serial established");
    
      token = strtok(mystring, ",");
      
      while (token != NULL) {
        SerialUSB.println(token);
        token=strtok(NULL, ",");
      }
    }

    The code works as expected on my Nano (with Serial instead of SerialUSB), but while it does compile for the Arduino Zero, it never makes it past printing “Serial established”. I have confirmed this by including code (serial print, LED flashing) past the tokenization parts, and these are never executed. The loop() function is never reached, it seems to halt at “token = strtok(mystring, “,”);”.

    I cannot think of a simpler possible way to test strtok(), but it’s just not working. Any help would be appreciated.

    #16763
    gryphacus
    Participant

    Well, I’ve solved the problem. I’m not sure how the code manages to execute on the Arduino Nano, but in reality it contains undefined behavior. Defining mystring as a char* implies it is constant, however strtok() and similar operations perform directly on the string. Obviously, this can’t be done if the string is constant.

    Simply modifying the code to redefine mystring as “char mystring[] = “…”;” is all that is required.

    #16764
    LIM PHANG MOH
    Keymaster

    Thank you for sharing the solution. As far I know, they always said strk() is not thread safe and outcome can be unpredictable. But your solution is what I usually use for declaring a pre-defined string.

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.