devil0150 devil0150 - 3 years ago 87
C Question

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?

rsp rsp
Answer Source

The man page of malloc say's:

The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

So, malloc() returns uninitialized memory, the contents of which is indeterminate.

 if (arr[i] != 0)

in your program, You have trying to access the content of memory block, which is invoked undefined behavior.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download