![](/img/trans.png)
[英]is it bad practise to use "void function()" in c in terms of error handling
[英]Error handling in a C, void returning function
給出這個例子的功能:
並且我只能更改函數中的else語句,我應該如何處理內存分配錯誤? 我不能返回一些錯誤代碼,因為函數返回void,我不能在C中拋出異常,我不能只是在一個函數中停止執行一個錯誤,這可能是相對於程序的其他東西而言是次要的做...我應該讓指針為NULL並讓調用我的函數后使用我的函數的編碼器處理錯誤?
我可以使用的唯一函數是這些庫中的函數:stdio.h,stdlib.h,string.h,stdarg.h
謝謝!
*p = NULL;
syslog(LOG_ERR, "Memory allocation error");
在課堂上我們做
printf("Error allocating memory.");
exit(1);
或者只是exit(1)
。 如果你的記憶已經滿了,你可以從那里做很多事情。
我應該讓指針為NULL並讓調用我的函數后使用我的函數的編碼器來處理錯誤嗎?
可能是。
但不僅是“ 之后 ”而且之前 ,編碼器需要存儲傳遞給你的函數指針的地址的副本。 因為如果編碼器沒有和你的功能失敗程序泄露內存,namly這樣的指向地址引用。
char * p = malloc(42);
{
char * p_save = p;
f(&p_save, "");
if (NULL == p_save)
{
/* log error or what ever is needed, including freeing p and return, exit or abort */
}
else
{
p = p_save;
}
}
free(p);
或者只是將生病的函數包裝成更容易處理的東西:
int fex(char ** pp, const char * t)
{
char * p = *pp; /* Store a backup, just in case. */
f(pp, t);
if (NULL == *pp)
{
*pp = p; /* Opps, restore ... */
return -1; /* ... and indicate error. errno should already have been set by realloc in f. */
}
return 0; /* Good. */
}
或者(有點臟):
char * fex(char * p, const char * t)
{
f(&p, t);
if (NULL == p)
{
return (char *) -1; /* ... and indicate error. errno should already have been set by realloc in f. */
}
return p; /* Good. */
}
稱后者為:
char * p = malloc(42);
{
char * tmp = fex(p, "");
if ((char *) -1) == tmp)
{
perror("fex() failed");
}
else
{
p = tmp;
}
}
free(p);
通常這樣處理如下:
abort();
在許多程序和庫的實現中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.