Query on memory-allocation semantics in "c_str"

Hi all.

I have a query; I think it would be best if I ask my query via some code :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string.h>

using namespace std;

string return_string()
{
        string s = "test";
        return s;
}


int main()
{
        if(strcmp(return_string().c_str(), "test") == 0)
        {   
                cout << "equal !!!!";
        }   
        else
        {   
                cout << "unequal !!!!";
        }   


        return 0;
}




In the above, (if I understand correctly), the call "return_string().c_str()" creates enough space on the stack, to store the returned string "test". However, I am confused, as to how is the space deallocated, as there is no variable holding the reference to the newly-dynamically-allocated-space-on-stack (which in turn means that there would be no automatic deallocation of stack-memory).

Would above code leak memory?





I am sorry if I am sounding idiotic, but I will be highly grateful if I could be cleared of my doubts.


Looking forward to a reply.


Thanks and Regards,
Ajay
Last edited on
As any value-returning function, return_string() creates a nameless temporary object, whose lifetime ends at the end of full expression (in this case, the full expression is "strcmp(return_string().c_str(), "test") == 0").
.c_str() is also a value-returning function, it creates a temporary pointer that points at the first character in the temporary string returned by return_string().
strcmp() receives that pointer, and follows it to examine the contents of the string (which is still fine, since the full expression didn't yet end). It is also a value-returning function and it returns a nameless int.

At the end of full expression (after ==0), the destructors for all temporaries are run in the order opposite of their construction: the int and the pointer are non-class types, so nothing needs to be done, but the string has a destructor, so it is executed.
Thanks Cubbi.
That was very well explained.... thanks a ton !!!!

Thanks again.


Thanks and Regards,
Ajay

Topic archived. No new replies allowed.