char* str = (char*)malloc(100*sizeof(char));
strcpy(str, ""); //Does this line initialize str to an empty string?
After calling line 1, does the allocated memory contain garbage? What about after calling line 2?
char* str = (char*)malloc(100*sizeof(char));
strcpy(str, ""); //Does this line initialize str to an empty string?
After calling line 1, does the allocated memory contain garbage? What about after calling line 2?
After calling line 1, does the allocated memory contain garbage?
It can contain anything, since malloc
per the standard isn't required to initialize the memory, and hence in most implementations shouldn't either. It will most likely just contain whatever data the previous "user" of that memory put there.
What about after calling line 2?
With that instruction you're copying a \0
character with "byte value" 0 to the first byte of the allocated memory. Everything else is still untouched. You could as well have done str[0] = '\0'
or even *str = '\0'
. All of these options makes str
point at an "empty string".
Note also that, since you tagged the question C
and not C++
, that casting the return value from malloc
is redundant.
malloc just provides a memory location creates a pointer to it and returns that. Initialization will not happen. You might get a junk value if the same memory was occupied by other stuff before.
Yes, malloc
returns uninitialized memory, and yes, your second line of code initializes your memory to an empty string.