i) I believe this function could cause a memory leak since the pointer s2 would be destroyed after returning from the function and its contents will thus become unusable. Am I correct? |
No. Memory leaks occur when you allocate memory (with new, or since this looks to be C, malloc/calloc) and forget/fail to unallocate it.
strcat does not allocate memory, so the above code does not allocate memory and therefore does not have any memory leaks.
ii) Also, does the function argument char *s get a copy of the string? |
No. 's' just points to a buffer. The buffer itself is not copied, only the pointer is.
Basically, you're modifying the exact same string that the calling function has. There is no copy.
strcat appends "Hello" onto whatever string pointed to by s.
So if s points to a buffer containing "Test", after the strcat call, s will contain "TestHello".
Doesn't the char pointer s also get deleted after returning from the function? |
No. Nothing here has anything to do with allocation/deallocation. Put that out of your mind.
Then what happens to the string that s is pointing to? |
It is being modified by strcat.
iii)Finally, I believe that the first statement of the function is an incorrect way to copy the string s |
You are right. That does not copy the string, it simply makes another pointer that points to the same string.
s1 and s2 both == s. All 3 pointers point to the same string. You don't even need s1 or s2 at all here.
It would be (far) better to dynamically allocate memory for s1 and then use strcpy to copy the string. Is this correct? |
No, because that would be passing ownership which is sloppy and leads to potential memory leaks.
it would be best to use strings:
1 2 3 4
|
std::string str(const std::string& s)
{
return s + "Hello";
}
|
That way you don't have to worry about these things. But if you are stuck with C and don't have strings, the next best thing, if you don't want 's' to be modified, would be to have a separate buffer passed to the function:
1 2 3 4 5
|
void str(char* s_out,const char* s_in)
{
strcpy(s_out,s_in); // copy the string from 'in' to 'out'
strcat(s_out,"Hello"); // append "Hello" to it
}
|