Reputation: 309
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
Reputation: 471
Instead of using malloc()
you could use calloc()
which automatically null terminates for you.
Upvotes: 0
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
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
Reputation: 1902
strcpy() functions copy the string including the terminating `\0' character, so you need +1.
Upvotes: 1