Search code examples
cpointersinitialization

When we call (char*)malloc(sizeof(char)) to allocate memory for a string, is it initialized? How to initialize?


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?


Solution

  • 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.