0

Unreliable conversion occurring when converting a C++ string to a const char* string.

The const char* string can get corrupted, depending on the string literal stored in the C++ string as well as the scope (I.E "label#" works, but not "Quadricopter_target#")

void myfunction(){
int i;
for(i=0; i<5; i++){
    const char* label;
    //Calculate target handle name
    if(i==0)
        label= "Quadricopter_target";
    else{//append a number to the label in additional instances
        string stringname = "Quadricopter_target#" + to_string(i-1);
        label = stringname.c_str();
        //this cout output does not get corrupted
        cout << "Label text: " << label << endl;
    }
    //this cout output gets corrupted
    cout << "Label text: " << label << endl;
}

Output using "Quadricopter_target#":
Label text: Quadricopter_target
Label text: ��Q
Label text: ��Q
Label text: ��Q
Label text: ��Q

Output using "label#":
Label text: label
Label text: label#0
Label text: label#1
Label text: label#2
Label text: label#3

This was compiled using C++11 using g++ on Ubuntu 16.04

Can someone please explain to me what I'm missing? Thanks in advance!

foorx
  • 13
  • 5

0 Answers0