There's at least two ways to do this:
malloc
method:
int main(void)
{
char *s = "abcde";
char *d = malloc(6);
char *r = memcp(d, s, 6);
printf("%s",r);
free(d);
return(0);
}
Array method:
int main(void)
{
char *s = "abcde";
char d[6];
memcp(d, s, 6);
return 0;
}
Note that it is generally not a good idea to hard code buffer lengths into your code (for example, you are hardcoding 6). If the size of your input changes and you forget to update the number 6, problems will occur.
The reason why you are getting a segmentation fault is because the pointer d
does not point to anywhere. In your memcp
function, you are trying to write this pointer but because it does not point anywhere meaningful your program crashes. In the C standard, this is called undefined behaviour, and basically it means anything can happen.
Also, it may interest you that there are already two functions available in the Standard C Library, memmove
and memcpy
. memmove
is useful if the source and destination areas overlap. If you know they won't ever overlap, memcpy
may be faster.
Lastly I would like to point out that you should not take the advice from Artur regarding uninitialised pointer usage. You should never rely on the value of an uninitialised pointer and doing so means your program's behaviour is not well-defined. Annex J of the C language specification mentions the following that is undefined behaviour:
J.2 Undefined Behaviour
- The behavior is undefined in the following circumstances:
- …
- The value of an object with automatic storage duration is used while it is indeterminate.
- …
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…