Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 517
Minh Tran Avatar asked Dec 05 '25 11:12

Minh Tran


1 Answers

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.

like image 156
Johann Gerell Avatar answered Dec 06 '25 23:12

Johann Gerell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!