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

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

问题描述

如果每个malloc()是否成功,应该检查一下? malloc()是否可能失败?那么会发生什么?



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

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

这是什么做法?我可以这样做:

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


解决方案

否需要转换 malloc()是的,需要检查malloc()是否成功
我们假设 malloc( )失败,您正在尝试访问指针,思考内存被分配将导致崩溃。因此,在访问指针之前,最好抓住内存分配失败。

  int * arr = malloc(sizeof(int)); 
if(arr == NULL)
{
printf内存分配失败);
return;
}


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, ie.:

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

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

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

解决方案

No need to cast malloc(). Yes 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(int));
if(arr == NULL)
{
printf("Memory allocation failed");
return;
}

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

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