Is malloc() initializing allocated array to zero?

Viewed 50029

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?

9 Answers

Zero's are assigned to page contents at first time in linux kernel.

Below program explains the memory initialisation difference in malloc and calloc:

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

#define SIZE 5

int main(void) {
    int *mal = (int*)malloc(SIZE*sizeof(int));
    int *cal = (int*)calloc(SIZE, sizeof(int));

    mal[4] = cal[4] = 100;

    free(mal); free(cal);

    mal = (int*)malloc(SIZE*sizeof(int));
    cal = (int*)calloc(SIZE, sizeof(int));

    for(int i=0; i<SIZE; i++) {
        printf("mall[%d] = %d\n", i, mal[i]);
    }
    for(int i=0; i<SIZE; i++) {
        printf("call[%d] = %d\n", i, cal[i]);
    }
}

I use malloc to allocate everything from the heap(dynamic memory) while i should use calloc instead nowaday , and memset is great for filling you memory segment with any chosen character.

Compile and work great with GCC:

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

int main() 
{

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

    memset(arr, 0, sz*sizeof(int) );


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

 free(arr);
 return 0;
}

ref: http://www.cplusplus.com/reference/cstring/memset/

well, the value is not initialized in malloc. And it does print "OK" in VS Code.

so in VS Code, the output is : "OK" followed by a garbage value.

in a web based compiler (here's the link : https://www.programiz.com/c-programming/online-compiler/ ),

the output was "LOL" followed by '0'

so some compilers do initialize the value..but actually the value in malloc is not intialized. so it will return a garbage value when printed as in the above example in VS Code.

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;
        }
        else
        {
            printf("LOL \n");
            break;
        }
    }

    printf("%d", arr[0]);

    free(arr);
Related