Link to home
Start Free TrialLog in
Avatar of perlperl
perlperl

asked on

std::string pointer

std::string *str1;
int main (int argc, char* argv[]) {

        process();
        printf("String = %s\n", str1->c_str());  // THIS SUCCEEDED 

}

void process() {
        std::string str;
        std::set<uint64_t> vals;
        vals.insert(12);
        vals.insert(14);
        for(std::set<uint64_t>::iterator it = vals.begin(); it != vals.end(); ++it) {
                str += boost::lexical_cast<std::string>(*it);
                str += ":";
        }

        str1 = &(str);
}

Open in new window


Why does the printf in the main() does not seg faults and prints correct value 12:14:

Shouldn't it seg fault as it is trying to access memory which is out of scope. I mean the variable str inside process() function goes out of scope once the control returns from the function
ASKER CERTIFIED SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of perlperl
perlperl

ASKER

I see.  I tried several times on my linux machine and it fails sometimes, so it all depends on if the memory was cleared during runtime or not.

Thanks
This is an example of what the C++ standard would defined as "undefined behaviour". This means that anything can happen. It might work, it might not - it all depends on the platform and the compiler and which way the wind is blowing at the time. Sufficed to say, this type of code is always considered defective.

The standard also defines "unspecified behaviour", which is also platform and compiler dependent; however, this will always behave exactly the same for a given compiler and platform. This type of code is not considered defective; however, it is considered bad practice to rely on such code.

You can read more on my blog: http://evilrix.com/2013/05/09/doubt-and-uncertainty/