0

I've managed to narrow down a problem with my code to this:

class A{
    private:
        int a;
    public:
        A(){};
        A(int i){a=i;};
        const char* str(){
            std::stringstream ss;
            ss << this << "->" << a;
            return ss.str().c_str();
        };
};
int main(){
    A test[2] = {A(42), A(99)};

    printf("%s,%s\n",test[0].str(),test[1].str());
    printf("%s,",test[0].str());
    printf("%s",test[1].str());
    return 0;
}

Which, quite surprisingly, prints this:

0x7ffff5b574a0->42,0x7ffff5b574a0->42
0x7ffff5b574a0->42,0x7ffff5b574a4->99

Why does this happen? Is it printf glitching? Please enlighten me.

Couchy
  • 753
  • 1
  • 5
  • 25
  • 7
    `ss.str().c_str()` creates a string, allocates memory, copies the data to that memory, returns a pointer to that memory. `;` then destroys that memory, destroys the string. Then you return a pointer pointing to where the words _used_ to be. – Mooing Duck Apr 29 '14 at 22:21
  • 1
    possible duplicate of [Can a local variable's memory be accessed outside its scope?](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – juanchopanza Apr 29 '14 at 22:21
  • @awesomeyi I expected the first line of output to be the same as the second, since I am printing the same objects. – Couchy Apr 29 '14 at 22:21
  • 1
    You're returning a a pointer to a buffer from an object that goes out of scope. Return a `std::string` instead and you'll see the expected output. – Marius Bancila Apr 29 '14 at 22:21
  • @MooingDuck Then howcome 42 is printed twice rather than 99, since doesn't 99 overwrite the previous buffer? – Couchy Apr 29 '14 at 22:25
  • @yoyo311: The second string is created in memory, then destroyed. Then the first is created in memory, (by _pure_ coincidence in the same location), and then destroyed. Then you are using the identical pointers to where both of those used to be, they hold (by _another_ pure coincidence) the value left there by the first string still. – Mooing Duck Apr 29 '14 at 22:28
  • 1
    And in case it isn't obvious, you should *never* rely on pure coincidences. If you're going to rely on luck, a lottery ticket is much more productive. – Mark Ransom Apr 29 '14 at 22:37
  • If you use `std::stringstream`, you might seriously consider using `std::cout` instead of `printf`. – tillaert Apr 29 '14 at 23:16

0 Answers0