在学校我们被告知要检查,即:
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()是否成功?
发布评论