In C programming: Do I need to consider '\0' (null terminator) when mallocing space for a new string
c, malloc
Solution
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`.
Problem
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) ```