1

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!

Zack
  • 385
  • 2
  • 3
  • 21

1 Answers1

2

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);
}
mcleod_ideafix
  • 11,128
  • 2
  • 24
  • 32
  • 1
    You are right: calling `realloc()` is enough. About error handling, well, the original `strcpy()` function does return a pointer to the destination string. Yours may do the same. – mcleod_ideafix Dec 08 '13 at 17:14