我应该检查 malloc() 是否成功吗? [英] Should I check if malloc() was successful?

查看:50
本文介绍了我应该检查 malloc() 是否成功吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否应该在每个 malloc() 之后检查是否成功?malloc() 是否有可能失败?那会发生什么?

Should one check after each malloc() if it was successful? Is it at all possible that a malloc() fails? What happens then?

在学校,我们被告知应该检查,即:

At school we were told that we should check, i.e.:

arr = (int) malloc(sizeof(int)*x*y);
if(arr==NULL){
    printf("Error. Allocation was unsuccessful. 
");
    return 1;
}

这方面的做法是什么?我可以这样做吗:

What is the practice regarding this? Can I do it this way:

if(!(arr = (int) malloc(sizeof(int)*x*y))
    <error>

推荐答案

无需强制转换 malloc().是的,但是需要检查malloc()是否成功.假设 malloc() 失败,并且您尝试访问指针,认为分配了内存会导致崩溃,因此最好在访问指针之前捕获内存分配失败.

No need to cast malloc(). Yes, however, it is required to check whether the malloc() was successful or not. Let's say malloc() failed and you are trying to access the pointer thinking memory is allocated will lead to crash, so it it better to catch the memory allocating failure before accessing the pointer.

int *arr = malloc(sizeof(*arr));
if(arr == NULL)
{
printf("Memory allocation failed");
return;
}

这篇关于我应该检查 malloc() 是否成功吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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