Vinayak
Vinayak

Reputation: 21

memory allocation for c_str function in string class

I have a member function of a class which is defined below, say

int x(std::string &a, std::string &b) {
    char *ptr = another_member.getStringMember().c_str() //I am storing the pointer 
    cout << ptr << endl;
    a="hello";
    cout << ptr << endl; 
}

The output is

StringMember

Hello

Can you please explain why this happens ?? Thanks

Upvotes: 2

Views: 887

Answers (5)

travis
travis

Reputation: 31

The temp std::string from another_member.getStringElement() goes out of scope after the line is executed. Change

char *ptr = another_member.getStringMember().c_str();

to

std::string s = another_member.getStringMember();
const char *ptr = s.c_str();

Upvotes: 1

David Jenks
David Jenks

Reputation: 1

Did you mean to do another_member.getStringElement().c_str() as against another_member.getStringElement.c_str().

Upvotes: 0

Lou Franco
Lou Franco

Reputation: 89152

You are not guaranteed that ptr is still usable after the a="hello" line (since it looks like they are the same string). In your case, since Hello was smaller, and the string wasn't being shared, it looks like it reused the space.

This is implementation specific behavior. It could have easily crashed.

Upvotes: 1

UncleBens
UncleBens

Reputation: 41331

Most likely because another_member.getStringMember and a are the same string.

In this case it is not actually legal to use ptr after the string has been modified with a="hello"; because mutating operations can make the previously obtained pointer invalid.

Upvotes: 5

PiotrK
PiotrK

Reputation: 4453

Just out of curiosity, do you call

x(another_member.getStringMember, fooBar);

?

c_str() returns internal pointer of string object which became invalid as soon as you modify the source string

Upvotes: 1

Related Questions