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?
OK
malloc
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() , .
malloc()
if (arr[i] != 0)
, undefined .
malloc .
, malloc, . . undefined, .
n1570-§6.2.6.1 (p5):
. lvalue, , undefined. [...]
:
, undefined, , .
, undefined. .
malloc . ?
40 .
calloc(), .
calloc()
arr = (int *)malloc(sz * sizeof(int));
arr = calloc(sz, sizeof(int));
C , , malloc() calloc() (a void *) , (int * ). , , malloc() calloc(), , C .
void *
int *
void *malloc(size_t size) . . , .
void *malloc(size_t size)
man-:
malloc() . . size 0, malloc() NULL, , free().
size
free()
calloc() memset() .
memset()
C 7.22.3.4:
#include <stdlib.h> void *malloc(size_t size);
malloc , .
. , , . , Microsoft Visual ++ Debug malloc() 0xCDCDCDCD, Release . GCC 0x000000, . , .
Debug
0xCDCDCDCD
Release
malloc(3) .
malloc(3)
unix/linux ( ), , , , ( , ).
, malloc , , malloc(3).
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.
Source: https://habr.com/ru/post/1682306/More articles:Вызов функции Javascript из html файла - javascriptЕсть ли параметр Numpy или Pandas для выдачи предупреждения при создании значения NaN - pythonCheck RFC 3161 timestamp response with PKIStatus value - javaSchema 'SA' does not exist and drops the table - javapython: The largest common divisor (gcd) for float, preferably in numpy - pythonКак правильно очистить массив в Haxe? - haxeStrange behavior using set.seed several times - randomIllegalStateException: this method cannot be called while RecyclerView computes the layout or scroll - androidGetting Gmail contacts in php - phpWhy is VBA code faster when called from a standard module (instead of a custom form)? - vbaAll Articles