sicklybeans
sicklybeans

Reputation: 309

In C programming: Do I need to consider '\0' (null terminator) when mallocing space for a new string

For example, suppose I want to copy thing the string "str1" to a new string, "str2":

void function(const char* str1){
    char* str2;
    str2 = (char *) malloc(sizeof(char) * (strlen(str1) + 1));
    strcpy(str2, str1);
    ...
}

Should the argument to malloc be:

sizeof(char) * (strlen(str1)+1)

or just:

sizeof(char) * strlen(str1)

Upvotes: 3

Views: 1274

Answers (4)

Nico Cvitak
Nico Cvitak

Reputation: 471

Instead of using malloc() you could use calloc() which automatically null terminates for you.

Upvotes: 0

ldav1s
ldav1s

Reputation: 16305

Yes, of course you have to account for the '\0'. So:

strlen(str1)+1U

Is what you want. Consider strdup in this case.

Upvotes: 1

Tommy
Tommy

Reputation: 100622

Yes, you need to +1 — strlen returns the string length; to store a string you need storage for its length plus an extra spot for the NULL terminator.

That being said, in this specific example (which I'm sure is just that: an example to make the point), you can just use strdup.

Upvotes: 6

Jack
Jack

Reputation: 1902

strcpy() functions copy the string including the terminating `\0' character, so you need +1.

Upvotes: 1

Related Questions