Serial Communication - strtok() issue I'm working on UART communication between an ESP32 (sender) and ESP8266 NodeMCU board(receiver). 

The host is sending out the following character string:

Serial.println("2753192144$1&amp;");


The 2753192144 is the payload. The $1&amp; is the trailer of the packet - $1 signifies a particular option for the receiver and &amp; is the termination character to signify that the packet is complete.

On the receiver end - this is what I have:

#define MAX_REC_STR_SIZE 10
#define REC_TRAILER_SIZE 4 // $1&amp; and string terminator
#define TRUE_TRAILER_SIZE 2 // option size really

void setup() {
  Serial.begin(9600);
}

void loop() {
    if(Serial.available()){
    char data [MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1];
    Serial.readBytesUntil('&amp;', data, MAX_REC_STR_SIZE + REC_TRAILER_SIZE); // data does not contain termination &amp;
    data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1] = 0; // adding null terminator

    // Tokenizing
    char *payload = strtok(data, "$"); // getting payload
    char opt = strtok(NULL, "$")[0]; // getting option - 1 in our sample

    // Print
    Serial.println(payload);
    Serial.println(opt);
  }
}


This code results in a stack exception error in the serial monitor. If I remove the last line which prints opt, the payload print works fine and I get 2753192144in the serial output. 

I tested this exact code out in a standard C compiler, except instead of the serial read part - I defined a character array with 2753192144$1&amp; and used printf instead of Serial.println. See the code below

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;

int main()
{
    char data[] = "2753192144$1";

    char *payload = strtok(data, "$");
    char opt = strtok(NULL, "$")[0];
    printf("Payload is %s and opt is %c", payload, opt);

    return 0;
}


This code outputs  

Payload is 2753192144 and opt is 1 


This works fine. Any ideas why the Arduino sketch isn't working?
data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1] = 0; // adding null terminator


That line places a 0 in the byte following the array. 

If you define an array of size [x] you have slices [0] to [x-1] available. If you try accessing [x] you will be altering other items on the stack after the array.

That's called a buffer overrun and is one of the most common causes of programs crashing.

If you want to put a 0 at the end of the array, you should use 

data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE] = 0; // adding null terminator


You should also check that the strtok() calls actually return a valid pointer. If the incoming string is not in the right format and strtok() can't split the string up, it will return NULL. If you then try and access that NULL pointer as if it were a valid array you will have a nasty crash.