Works on Solaris but not on Linux ! Any idea why?


I have this following piece of code:

int id = 5;
const char *ptrId;

ptrId =  ( int_to_str(id) ).getPtr();  // Works in Solaris well  

But the above code prints some junk values when I run the same on Linux machine. But the following works well on Linux:
String temp = int_to_str(id);
ptrId = temp.getPtr();

The prototype of getPtr() is:
const char* String::getPtr() const

Any idea why it is so?
What does the pointer returned by String::getPtr() point to? Is it pointing to a member of String? If so, in your first example, it's pointing at a member of an object that has been destroyed, in the second example it's pointing at a member of the object that still exists (under the name "temp").

(aside of this guess, do post more code)
Last edited on
Undefined behavior will not produce the same results on every kind of machine. That is why we use the term "undefined". Is getPtr coded correctly? How would we know since we can't see its definition?

If I understand things correctly, you are calling a function on a temporary object that is constructed but not assigned to a variable in the first example. I'm assuming you compiled for each machine so look at the assembly and see if the temp is being destroyed at a different time? I would never trust code like example 1 without first having a detailed understanding of the C++ std. When exactly will the system return that memory to stack and destroy the object along with the underlying string? Example 1 just looks like a bad idea. Perhaps you should consider making a static template function that uses stringstream to do the conversion rather than using a class that has to be constructed.
Topic archived. No new replies allowed.