我已经看到了几种不同的方法来进行malloc错误检查.有一种方式比另一种更好吗?有些退出代码比其他代码更好吗?使用fprintf和stderr比使用printf语句更好吗?使用退货而不是退出更好?
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(1);
}
res = malloc(strlen(str1) + strlen(str2) + 1);
if (!res) {
fprintf(stderr, "malloc() failed: insufficient memory!\n");
return EXIT_FAILURE;
}
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(-1);
}
ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(EXIT_FAILURE);
}
char *ptr = (char *)malloc(sizeof(char) * some_int);
if (ptr …Run Code Online (Sandbox Code Playgroud)