我应该检查malloc()是否成功?

编程入门 行业动态 更新时间:2024-10-28 06:22:07
本文介绍了我应该检查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()是否成功?

本文发布于:2023-11-07 15:05:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1566774.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:malloc

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!