4

I have the following code:

int *p;

p = (int*)malloc(sizeof(int) * 10);

but what is the default value of this int array with 10 elements? are all of them 0?

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
user2131316
  • 3,111
  • 12
  • 39
  • 53
  • 3
    Why not read the manual page - http://linux.die.net/man/3/malloc โ€“ Ed Heal Jul 03 '13 at 09:40
  • First few lines "Description The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. " โ€“ Ed Heal Jul 03 '13 at 09:44
  • 1
    [Don't cast the return value of `malloc()` in C](http://stackoverflow.com/a/605858/28169). โ€“ unwind Jul 03 '13 at 09:47

5 Answers5

13

The real content is indeterminate.

C11, ยง 7.22.3.4 The malloc function

The malloc function allocates space for an object whose size is specified by size and whose value is indeterminate.

However, the operating system often initializes this memory space to 0 (see this answer). You can use rather calloc to be sure that every bits are setted to 0.

Community
  • 1
  • 1
md5
  • 23,373
  • 3
  • 44
  • 93
5
are all of them 0?

No, malloc does not initialize the memory allocated, use calloc in order to initialize all values to 0

int *p;
p = calloc(10, sizeof(int));
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
2

It's undefined. Using calloc( ) instead then the allocated buffer is defined to be filled with binary 0

Ingo Leonhardt
  • 9,435
  • 2
  • 24
  • 33
1

The "default" value of an element created with malloc is the value stored at this point in your memory (often 0 but you can have other values, if an another program wrote in this place). You can use calloc, or after the malloc, you can memset your var. And don't forget to verify the value of your pointer, check if it's not NULL.

audisi_r
  • 158
  • 2
  • 7
0

You need to use calloc() for this purpose. malloc() allocats only memory, so this memory contains garbage values by default.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63