We must assume that a
is NUL terminated (ending with '\0'
), otherwise we can't be sure about its size/length (unless you know the length of a
yourself).
char *a = "Hello World"; /* say for example */
size_t len = strlen(a)+1; /* get the length of a (+1 for terminating NUL ('\0') character) */
Note that, if you know the length of the string pointed to by (or saved in) a
then you will assign it to len
, instead of using the above statement.
char *b = calloc(1, len); /* */
memcpy(b, a, len); /* now b contains copy of a */
If your intention is just to make a copy of a string (NUL terminated), you can use strdup()
(declared in string.h
):
char *b = strdup(a); /* b now has a copy of a */
NOTE: strdup()
is in POSIX. If you want strict ANSI C then you can make a wrapper like following as I mentioned earlier:
unsigned char *my_strdup(const unsigned char *a)
{
size_t len = strlen(a)+1;
unsigned char *b = calloc(1, len);
if (b) return (unsigned char *) memcpy(b, a, len);
return NULL; /* if calloc fails */
}