Assigned string value is different than returned value

Hi,

My simplified code is the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

function blablabla(){ ....

    for(int i=0; i<2; i++){
        for (int j = 0+4*i; j<4+4*i; j++){
            string first = "histogram";
            cout << first << j << endl;
            const char* name = nameHist(first, j);
            cout << "IN FUNCTION " <<__FUNCTION__<< " returned value is " <<  name << endl;
    }
}

const char* nameHist(string first, int number){
    cout << "ENTERING " << __FUNCTION__ << " with number " << number << endl;
    ostringstream name;
    name << first << number;
    
    cout << "AT LINE" << __LINE__ << " RETURNING "<<(name.str().c_str()) << endl;

    return (name.str().c_str());
}


When executing this code, this is my output:

1
2
3
ENTERING nameHist with number 7
AT LINE392 RETURNING histogram7
IN FUNCTION blablabla returned value is histogram0


I am completely clueless how this is possible. I can actually see it returning histogram7 and when I assign this in the other function, it is changed to histogram0. I need it as a const char*, it is no solution to change everything to strings.

If anyone can help me with this, thanks.

P.S. this doesn't work for the numbers 3, 5, 6 and 7. For the numbers 0, 1, 2 and 4 it DOES work.

Last edited on
The object ostringstream name; is created in the function nameHist. When that function ends, the object is destroyed. You are returning a pointer to somewhere that used to be the object's data (or rather in this case, used to be the data of a copy of a string associated with the object, but the principle is identical - a pointer to data that effectively no longer exists). Because the object has been destroyed, there is no guarantee about what will be in that memory. It might be the leftover remnants of the object, just because nothing else has used that memory yet. It might be something else entirely.

If you simply must have a const char*, either return the string and use the c_str() function as you need it, or use dynamic memory (new) to ensure that the objects you care about live on after the function ends.
Last edited on
Topic archived. No new replies allowed.