在每次使用 malloc()
之后,是否应该检查它是否成功?malloc()
是否会失败?如果失败会发生什么?
在学校里,我们被告知应该进行检查:
arr = (int) malloc(sizeof(int)*x*y);
if(arr==NULL){
printf("Error. Allocation was unsuccessful. \n");
return 1;
}
这方面有什么惯例吗?我可以这样做吗:
if(!(arr = (int) malloc(sizeof(int)*x*y))
<error>
arr = (int) malloc(...)
是错误的,malloc
返回一个指针。除此之外:是的,你应该检查它是否失败,因为它可能会失败。另外,强制转换其返回值是有害的。 - The Paramagnetic Croissant