Search code examples
cstringmalloccalloc

When assigning memory dynamically in C for strings, do you count the \0 end of string char?


When assigning memory dynamically in C for strings, do you count the \0 end of string char?

char *copyInto, *copyFrom="test";

// Should 
copyInto = (char*)malloc(strlen(copyFrom));
// suffice?

// or should this be the following?
copyInto = (char*)malloc(strlen(copyFrom)+1);

// assuming you want to copy the string from copyFrom into copyInto
strcpy(copyInto,copyFrom);

// Does anyone recommend just \0-ing the whole copyInto as in
copyInto = (char*)calloc(strlen(copyFrom)+1);
// and if so, should it still be (strlen(copyFrom)+1) size?

Solution

    1. Don't cast the return values of malloc() or calloc() (or realloc() for that matter) in a C program.
    2. Yes, you need to have the +1.
    3. Why bother using calloc() to zero out the whole string if you're just going to copy into it immediately? Seems like a waste of cycles to me.