I'm trying to split a char* using strtok. This is the code:
#include <string.h>
char** splitValues;
char* to_split;
int times = 0;
int counter;
void setup() {
Serial.begin(9600);
}
void loop() {
to_split = "00;11;22;33;44;55";
if(times == 0){
counter = 0;
for(char* temp = strtok(to_split, ";"); temp != NULL; temp = strtok(NULL, ";")){
Serial.println(temp);
// splitValues[counter] = temp;
// counter++;
}
times = 1;
}
}
This is working fine and outputs all the string split by ";"
But if I add the two commented rows, the program goes in loop and keeps printing the first value of temp.
I don't understand how these two rows can loop the program.
Sorry, I edited the post.
I didn't post the full code because it's quite longer than this, but trying to compile this example does exactly the same thing my code does.
Looks like splitValues is a pointer to a pointer that is pointing into nowhere.
Delta_G:
char** splitValues;
splitValues is just a pointer to a pointer that is pointing to nowhere. There isn't any memory reserved to put anything anywhere from this.
And yet:
splitValues[counter] = temp;
You try to put something there. So this writes over some unknown bit of memory out of bounds and causes undefined behavior.
Instead, splitValues should be defined as an array large enough to hold whatever you want to put there.
char* splitValues[NumberOfTokensYouExpect];
Thank you, this solved my problem.
Now my question is: what should I do if I need to change the size of this vector during runtime after the vector was declared?