How to allocate the array before calling strcpy?
Given:
char test[] = "bla-bla-bla";
Which of the two is more correct?
char *test1 = malloc(strlen(test));
strcpy(test1, test);
or
char *test1 = malloc(sizeof(test));
strcpy(test1, test);
Solution 1:
This will work on all null-terminated strings, including pointers to char
arrays:
char test[] = "bla-bla-bla";
char *test1 = malloc(strlen(test) + 1);
strcpy(test1, test);
You won't get the correct size of the array pointed to by char*
or const char*
with sizeof
. This solution is therefore more versatile.
Solution 2:
Neither:
#include <string.h>
char *mine = strdup(test);
Solution 3:
You should use strlen
, because sizeof
will fail silently if you change test to be a run-time defined string. This means that strlen
is a far safer idea than sizeof
as it will keep working.
Solution 4:
char test[]="bla-bla-bla";
char *test1 = malloc(strlen(test) + 1); // +1 for the extra NULL character
strcpy(test1, test);