user10497670
user10497670

Reputation:

String Copy in C

I have a function which I pass a character pointer to, like:

funtion_name (char* string){
...
}

I want to copy the string to a temporary string variable, then copy that into a struct. This is what I have done thus far:

char* namecpy = malloc(strlen(string+1));
strcpy(namecpy, string);
strcpy(ptr->name, namecpy);

This is giving me a segmentation fault when I call the function. I think it's because I'm not allowed to directly copy into the struct variable... but how else would I have to copy it?

Upvotes: 0

Views: 799

Answers (2)

selbie
selbie

Reputation: 104569

You can combine the malloc and strcpy together with the strdup function. (#include <string.h>)

ptr->name = strdup(string);

don't forget to call free on ptr->name after you are done with it.

Upvotes: 0

tadman
tadman

Reputation: 211690

You're copying it twice and presumably the second target, ptr->name isn't allocated properly so it crashes.

What you mean to do is this:

ptr->name = malloc(strlen(string)+1);
strcpy(ptr->name, string);

Allocate the buffer at the target location. Don't mess around with temporary variables unless you absolutely have to.

Every buffer you write to must have sufficient memory allocated to it in advance. C isn't going to check this for you, it will do exactly what you ask without hesitation, so like when operating a dangerous piece of equipment like a chainsaw you must pay very close attention to how you're using it.

Upvotes: 1

Related Questions