简体   繁体   中英

strcpy when having char pointers in C

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 ?

It needs to be:

abc.charptr = malloc(strlen(name)+1); ?
strcpy(abc.charptr, name);

The return value of strlen doesn't include space for the null zero '\\0' at the end of the string.

You will also have to free your allocated memory at some point.

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() .

abc.charptr = (char *) malloc(strlen(name) + 1);

Note the +1, since you need space for the null terminator. Then strcpy() will be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM