1

I have an Arduino that is processing a string by splitting it into an array. For some reason, however, after the processing function returns, the array can only be accessed once before it appears that the values become corrupted. In other words, I can access any element of the array, but when I do, I am unable to access any other elements of the array.

void loop(){
  int pin;
  Serial.print("Enter command: ");
  while(Serial.available()<=0)
    delay(100);
///Input to the serial terminal was: "This;is;a;command". Notice how inside the getCommands() function, it will output all elements ok

  char** commands = getCommands();
  Serial.println(commands[1]); ///prints "is"
  Serial.println(commands[0]); ///**** prints nothing, or sometimes infinite spaces****
  delay(1000);
}
char** getCommands(){
  char* commandIn = getSerialString();
  char* commands[10];
  char *str;
 int i=0;
 while ((str = strtok_r(commandIn, ";", &commandIn)) != NULL){

   commands[i]=str;
   i++;
}
Serial.println(commands[0]);   ///prints "This"
Serial.println(commands[1]);   ///prints "is"
Serial.println(commands[2]);   ///prints "a"

return commands;
}
char* getSerialString(){
  while(Serial.available()<=0)
    delay(100);
  int i=0;
  char commandbuffer[100];
  for(int a=0; a<100; a++)
    commandbuffer[a]='\0';

  if(Serial.available()){
     delay(100);
     while( Serial.available() && i< 99) {
        commandbuffer[i++] = Serial.read();
     }
     commandbuffer[i++]='\0';
  }
  return commandbuffer;
}

1 Answer 1

3
char** getCommands(){
  char* commands[10];
  …
  return commands;
}

The statement return commands doesn't return the value of the array, it returns the address of the array. Technically, the type of the expression commands decays from array-10-of-pointer-to-char to pointer-to-pointer-to-char in this context; the value of the expression is the address of the first element of the array.

As a result, you return the address of a local variable, which local variable ceases to exist after the return statement. Later, in loop, you dereference this pointer to a destroyed object, resulting in undefined behavior.

1
  • Perfect, thanks so much! I'm a C++ newbie, this fixed it perfectly! Commented Mar 22, 2012 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.