Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcpy when having char pointers in C

Tags:

c

string

char

I have a simple doubt in char arrays. I have a structure:

struct abc {
char *charptr;
int a;
}

void func1()
{
    func2("hello");
}

void func (char *name)
{
    strcpy(abc.charptr, name); // This is wrong. 
}

This strcpy will result in a crash since I do not have any memory allocated to the charptr. The question is : For mallocing this memory, can we do

abc.charptr = (char *) malloc(strlen(name)); //?
strcpy(abc.charptr, name); // Is this (or strncpy) right ?

Is this right ?

like image 725
Vin Avatar asked Jul 20 '26 08:07

Vin


1 Answers

If you were to use malloc() you need to remember to make room for the null-terminator. So use malloc(strlen(name)+1) before calling strcpy().

But in this case you should just use strdup() which does the allocation and copying in one go:

abc.charptr = strdup(name);

The memory returned by strdup() has been allocated with malloc() and hence must be disposed of with a call to free().

like image 111
David Heffernan Avatar answered Jul 21 '26 23:07

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!