【发布时间】:2014-05-01 12:03:27
【问题描述】:
例如考虑以下代码:
int main(int argc,char *argv[])
{
int *p,*q;
p = (int *)malloc(sizeof(int)*10);
q = (int *)malloc(sizeof(int)*10);
if (p == 0)
{
printf("ERROR: Out of memory\n");
return 1;
}
if (q == 0)
{
printf("ERROR: Out of memory\n");
exit(0);
}
return 0;
}
return 0、return 1、exit(0) 在上述程序中做了什么?
exit(0) 将退出整个程序,并且控制退出循环,但在 return 0、return 1、return -1 的情况下会发生什么。
【问题讨论】:
-
你也必须看到这个 - Difference between exit and return
-
首先,从内存分配失败返回的
exit(0)给人一种错误的安慰感,因为它几乎肯定应该是exit(EXIT_FAILURE)(毕竟,程序确实只是轰炸了一个内存-分配)。 -
exit是标准库函数,所以如果你使用它需要#include,如果你使用 return则不需要