How to allocate the array before calling strcpy?

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.

Leave a Comment