malloc 像 calloc 一样工作

Rec*_*cep 0 c malloc memory-management calloc

malloc 运行时,会生成内存块,不设置任何值,包含垃圾值。当 calloc 运行时,会像 malloc 函数一样发生一些事件,但有一个区别。当 calloc 生成新块时,它在块中设置 0(零)。

#include <stdio.h>
#include <stdlib.h>
int main(void){
    int i,j;
    int* array1 = (int*)malloc(sizeof(int)*5);
    int* array2 = (int*)calloc(sizeof(int),5);
    for(i = 0; i < 5; i++){
        printf("%p: %d\n",&array1[i],array1[i]);
    }
    printf("===================\n");
    for(j = 0; j < 5; j++){
        printf("%p: %d\n",&array2[j],array2[j]);
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

根据此信息,前五个值必须包含垃圾值(实际上它应该看起来像随机数据),后五个值必须为零。但是当这段代码在 Windows 中运行时,没有问题,但是当这段代码在 Linux 中运行时,这种情况不会发生。我以为是ASLR还是DEP保护,我把ASLR关掉了,用旧的Linux系统做DEP保护,结果还是一样。最后,我认为它可能取决于 C Standard,并且我在编译 Code 时更改了 C Standard,但结果并没有什么不同。我问这是什么原因。

Iho*_*huk 6

malloc不会用零填充数据(如您所料)。但不能保证垃圾数据不为零。所以没关系,如果你分配内存并看到所有字段有时或在某些情况下都归零。我假设你会在“分配的”内存中看到“更多随机”的数据,如果大小会更大,或者如果你要分配,用 smth 填充,释放,再次分配。但是calloc即使经过这样的操作,您仍然会看到归零的内存。