Click here to Skip to main content
15,891,908 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
const char* append(const char* s1, const char* s2) {
string s(s1);
s += s2;
return s.c_str();
}

void foo() {
const char* total = append("abc", "def");
}

What I have tried:

Please let me know if there is any problem in this code?
Posted
Updated 14-May-18 3:32am
Comments
Mehdi Gholam 13-May-18 13:58pm    
Does it work?
[no name] 13-May-18 14:03pm    
It works still there is some bug in this which I am not able to find out.

It is a mistake really no good style to return the pointer of a deallocated object when the functions scope is left. In such a simple scenario (string class) it may work, but it is wrong. Some destructors may delete that pointed resource and you have a crash.

The function makes no sense, because the operation can be written in a line.
 
Share this answer
 
v2
Comments
CPallini 13-May-18 16:40pm    
5.I would call 'mistake', such 'bad style'.
KarstenK 14-May-18 7:29am    
Ofcourse you are right. => Corrected
Because the scope of the string s is only within the function append. As soon as that function returns, the string destructor will be called and the memory containing the characters released. That means that the space that was occupied may immediately be overwritten by some other data.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900