Is malloc () initializing the allocated array equal 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 does not print OK. mallocmust not initialize allocated memory to zero. Why is this happening?

+5
source share
7 answers

The malloc man page says:

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

, malloc() , .

 if (arr[i] != 0)

, undefined .

+9

malloc .

, malloc, . . undefined, .

n1570-§6.2.6.1 (p5):

. lvalue, , undefined. [...]

:

, undefined, , .

, undefined. .

+6

malloc . ?

40 .

calloc(), .

:

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

:

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

C , , malloc() calloc() (a void *) , (int * ). , , malloc() calloc(), , C .

+3

void *malloc(size_t size) . . , .

man-:

malloc() . . size 0, malloc() NULL, , free().

calloc() memset() .

+2

C 7.22.3.4:

#include <stdlib.h>
void *malloc(size_t size);

malloc , .

. , , . , Microsoft Visual ++ Debug malloc() ​​ 0xCDCDCDCD, Release . GCC 0x000000, . , .

+2

malloc(3) .

​​unix/linux ( ), , , , ( , ).

, malloc , , malloc(3).

0

did you decide that? This happened to mine, with gcc-5.4. I continued to use the wrong access until the system interrupted the process, but none of the selected ones got a non-zero value, even with "-O3" ... This seems rather strange since I unloaded the RAM before starting my demo, finding that most parts are non-zero.

0
source

Source: https://habr.com/ru/post/1682306/


All Articles