Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is malloc() initializing allocated array to zero?

Here is the code I'm using:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int sz = 100000;
    arr = (int *)malloc(sz * sizeof(int));

    int i;
    for (i = 0; i < sz; ++i) {
        if (arr[i] != 0) {
            printf("OK\n");
            break;
        }
    }

    free(arr);
    return 0;
}

The program doesn't print OK. malloc isn't supposed to initialize the allocated memory to zero. Why is this happening?

like image 351
devil0150 Avatar asked Jul 26 '17 10:07

devil0150


People also ask

Does malloc initialize to zero?

malloc() doesn't initialize the allocated memory. If you try to read from the allocated memory without first initializing it, then you will invoke undefined behavior, which will usually mean the values you read will be garbage. calloc() allocates the memory and also initializes every byte in the allocated memory to 0.

Which function initialize the allocated memory to zero?

calloc will initialize the memory to zero. So, the allocated memory area will be set to 0.

Does malloc return zeroed memory?

malloc returns a void pointer to the allocated space, or NULL if there's insufficient memory available. To return a pointer to a type other than void , use a type cast on the return value.

Which of the following will initialize the new memory to 0?

(A) calloc() allocates the memory and also initializes the allocates memory to zero, while memory allocated using malloc() has uninitialized data.


1 Answers

malloc isn't supposed to initialize the allocated memory to zero. Why is this happening?

This is how it was designed more than 40 years ago.

But, at the same time, the calloc() function was created that initializes the allocated memory to zero and it's the recommended way to allocate memory for arrays.

The line:

arr = (int *)malloc(sz * sizeof(int));

Should read:

arr = calloc(sz, sizeof(int));

If you are learning C from an old book it teaches you to always cast the value returned by malloc() or calloc() (a void *) to the type of the variable you assign the value to (int * in your case). This is obsolete, if the value returned by malloc() or calloc() is directly assigned to a variable, the modern versions of C do not need that cast any more.

like image 151
axiac Avatar answered Oct 18 '22 21:10

axiac