Yes, memory you get back from malloc
is uninitialized. In general, it will contain unpredictable, random values. By chance the random values might be 0 -- but you can't count on this at all.
So, yes, if you care, you must always initialize the memory you get back from malloc
. One way is by calling memset
-- although the example you posted is unusual. If you want to zero out all the memory you just got back, the usual call would be
memset(assign_value, 0, 10);
(Instead of malloc
, you can also use calloc
. Once difference between malloc
and calloc
is that calloc
does automatically initialize the newly-allocated memory to all 0.)
If you're using assign_value
as a string, and you want to have it start out as an empty string, you don't have to zero out all of it. It's sufficient just to put a null character in the first position:
*assign_value = '\0';
Once you do any of these things, assign_value
will hold an empty string, with a length of 0. So your test if(strlen(assign_value) == 0)
will always succeed, and in your later code you'll always end up calling strcpy
, never strcat
.
Finally, as side points, you don't have to multiply by sizeof(char)
, or cast the result, when calling malloc
. So you could use the simpler:
char *assign_value = malloc(10);
(You don't have to multiply by sizeof(char)
because sizeof(char)
is, by definition, always exactly 1. You don't have to explicitly cast the result of malloc
in C, and if you do, it can hide errors.)