7

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?

3
  • 3
    Why not read the manual page - linux.die.net/man/3/malloc Commented Jul 3, 2013 at 9:40
  • First few lines "Description The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. " Commented Jul 3, 2013 at 9:44
  • 1
    Don't cast the return value of malloc() in C. Commented Jul 3, 2013 at 9:47

5 Answers 5

15

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.

Sign up to request clarification or add additional context in comments.

Comments

6
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));

Comments

3

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

Comments

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.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.