Reputation: 12621
#include<stdio.h>
char* my_strcpy(char* source, char* destination) {
char* p = destination;
while( *source != '\0' ) {
*p++ = *source++;
}
*p = '\0';
return destination;
}
int main() {
char stringa[40] = "Time and tide wait for none";
char stringb[40];
char *ptr;
char *ptr1;
ptr = stringa;
ptr1 = stringb;
puts(stringa);
puts(ptr);
my_strcpy(ptr, ptr1);
puts(ptr);
return 0;
}
Here the variable destination
, as the local copy of the function, is returning the pointer is safe. I believe it will be safe as long as the address is used immediately after returning or else what if some other process uses the address, it will be changed.
How to return safely without doing return destination
?
Is it possible to do a malloc for p
and return it rather than assigning the location pointed by destination
?
Upvotes: 0
Views: 134
Reputation: 15397
destination
isn't controlled by my_strcpy
, so what happens to it outside of the function is irrelevant to my_strcpy
. That is to say, it's perfectly safe and expected for the function to return destination
. Whoever called my_strcpy
will be responsible to make sure the variable's memory is ok. Returning the destination
variable is simply a convenience for function chaining.
You could malloc and return a new area of memory (though then you wouldn't need a destination
parameter). This is basically the functionality of strdup
, and it's the responsibility of the caller of strdup
to free the memory that was allocated.
Note, there's no risk of another process corrupting the memory. Unless you're dealing with shared memory, processes each have access to only their memory. Some function later on in this process could change what you did in my_strcpy
, but that's not the problem of my_strcpy
. As for it being safe if it's used immediately after the function, you're copying into space that was assigned to you. The p
value isn't the memory you're writing into; it's just the pointer to the memory. And the memory itself isn't on the stack. As jpw mentioned at some point - you don't need the p
variable at all.
Upvotes: 3