malloc() 是否将分配的数组初始化为零? [英] Is malloc() initializing allocated array to zero?

查看:40
本文介绍了malloc() 是否将分配的数组初始化为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的代码:

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
");
            break;
        }
    }

    free(arr);
    return 0;
}

程序不打印OK.malloc 不应该将分配的内存初始化为零.为什么会这样?

The program doesn't print OK. malloc isn't supposed to initialize the allocated memory to zero. Why is this happening?

推荐答案

malloc 的手册页 说:

malloc() 函数分配 size 个字节并返回一个指向分配的内存.内存没有初始化.如果size为0,然后 malloc() 返回 NULL 或唯一的指针值,它可以稍后被成功传递给free().

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().

所以malloc()返回未初始化的内存,其内容是不确定的.

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

 if (arr[i] != 0)

在你的程序中,你试图访问一个内存块的内容,它被调用undefined behavior.

In your program, You have tried to access the content of a memory block, which is invoked undefined behavior.

这篇关于malloc() 是否将分配的数组初始化为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆