Reputation: 385
if I would call the strcpy function like this:
char *s = NULL;
strcpy(&s, "Test");
in the main function, would this be the best implementation of it: or there is a better way to implement the function? Thank you!
Upvotes: 1
Views: 463
Reputation: 11428
First of all: if you take sizeof(src)
you will alloc memory for a pointer, not for a string. In 32 bit environments, this will leave you with 4 bytes of memory, and not 10 as you need.
Therefore, you need to supply how much memory do you need, or infere it from your second argument: something like this:
void str_cpy(char** dest, const char* src){
if (*dest == NULL) *dest = malloc(strlen(src)+1);
else *dest = realloc(*dest, strlen(src)+1);
memcpy(*dest, src, strlen(src) + 1);
}
Upvotes: 2