3
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?

m.s.
  • 16,063
  • 7
  • 53
  • 88
Minh Tran
  • 494
  • 7
  • 17
  • 1
    Possible duplicate of [Why does malloc initialize the values to 0 in gcc?](http://stackoverflow.com/questions/8029584/why-does-malloc-initialize-the-values-to-0-in-gcc) – m.s. Oct 19 '15 at 08:21
  • `man malloc` will tell you. – cmaster - reinstate monica Oct 19 '15 at 08:26
  • Consider using [strdup](http://man7.org/linux/man-pages/man3/strdup.3.html) or [asprintf](http://man7.org/linux/man-pages/man3/asprintf.3.html) if your system have them.. – Basile Starynkevitch Oct 19 '15 at 08:34
  • the expression: `sizeof(char)` is defined by the standard to be 1 and multiplying by 1 has absolutely no effect on the parameter passed to malloc(). All it does is clutter the code. – user3629249 Oct 19 '15 at 08:56
  • 2
    if you want the malloc'd memory to be initialized to all '\0's then use `calloc()` rather than `malloc()`. In all cases, check (!=NULL) the returned value to assure the operation was successful. In C, do not cast the returned value, because it is a `void*` type so can be assigned to any pointer. casting the returned value just clutters the code and creates headaches when maintenance is performed – user3629249 Oct 19 '15 at 08:58

3 Answers3

5

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.

Johann Gerell
  • 24,991
  • 10
  • 72
  • 122
2

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.

shankar
  • 21
  • 3
1

Yes, malloc returns uninitialized memory, and yes, your second line of code initializes your memory to an empty string.

Jim Buck
  • 20,482
  • 11
  • 57
  • 74