Skyler Gunn Skyler Gunn - 1 year ago 90
C Question

Can I emulate strcpy using malloc?

I'm trying to make a strcpy function from scratch for a class. While I could do it with a for loop and copy the individual characters, I think I could just make a swap using malloc and pointers to make it more efficient. Here's my code, but I've been getting a lot of confusing errors.

void notStrcpy(char s1[], char s2[]) { //copies string s1 into s2
char *s3 = (char *) malloc(strlen(s1)); //s3 is now an alias of s1
s2 = *s3;} //dereference s3 to dump s1 into s2

Why is this happening, and is there any way to make this code work the way I intended it?

Answer Source

You cannot do that: strcpy expects both chunks of memory to be ready - one for reading the string, and the other one for writing the string. Both addresses are expected to have enough memory for the actual content of a null-terminated C string.

On the other hand, malloc gives you a third chunk of memory (you need to allocate strlen(s)+1, but that's a completely different story). String copy algorithm has no use for that chunk of memory. On top of that, assigning parameters of a function has no effect on the values passed into your function, so s2 = *s3 is not doing what you think it should be doing.

Long story short, while ((*s1++ = *s2++)); is your simplest strcpy implementation.

Note: malloc could come in handy in an implementation of string duplication function, e.g. strdup. If you decide to give it a try, don't forget to allocate space for null terminator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download