I have a simple doubt in char
arrays. I have a structure:
struct abc {
char *ch开发者_StackOverflowarptr;
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 malloc
ing this memory, can we do
abc.charptr = (char *) malloc(strlen(name)); //?
strcpy(abc.charptr, name); // Is this (or strncpy) right ?
Is this right ?
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()
.
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.
abc.charptr = (char *) malloc(strlen(name) + 1);
Note the +1, since you need space for the null terminator. Then strcpy() will be fine.
精彩评论