[英]How to use assert corectly in this function?
我有以下功能,並且在兩個地方都使用了assert
。 我想知道我在哪里以錯誤的方式使用assert以及為什么。 第一個是錯誤的,因為我們不能在用戶輸入上使用assert。 第二個:我們可以使用assert來檢查malloc
成功嗎? 其余的我仍然不知道為什么。 你能幫忙嗎? 我想簡短地解釋在給定的位置上assert
。
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <malloc.h>
#define num 10
int hh(char *);
您可以定義對與錯,這取決於您,但是作為一般規則,您不希望在斷言中使用程序邏輯(因此,檢查輸入字符串的長度是一種不好的用法)。
請記住:assert僅在調試模式下處於活動狀態,因此,如果您依靠它進行錯誤檢查(幾乎像所有示例一樣),則在發布模式下會發生奇怪的事情。
即assert通常是一個定義,例如:
/* assert() only does something if NDEBUG is NOT defined */
#ifdef NDEBUG
#else
#define assert(x) _assert(x)
#endif
請參閱-DNDEBUG通常來自哪里? 有關NDEBUG的更多信息
您絕對不想使用斷言來更改流程,例如
assert(some_function()); /* some_function only called if NDEBUG is not defined */
使用assert
來檢查malloc
的返回:如果未定義NDEBUG,則檢查不會完成,因此從理論上講,您可以退出並訪問NULL指針。 我會說這不安全。 請參閱使用斷言處理錯誤檢查更多討論。
讓我們通過簡單的“僅在調試中”過濾器一一看待您的斷言:
assert(argc==2);
/*
* If NDEBUG is defined and argc == 1 you get through,
* so anything that uses argc[1] will give undefined behavior.
* = BAD USE
*/
char *s = malloc(N);
/* 2 */
assert(s!=NULL);
scanf("%s", s
/*
* If NDEBUG is defined and malloc fails you keep going and read into
* NULL = undefined behaviour = BAD
*/
assert(strlen(s)<N);
/*
* If NDEBUG is defined keeps going even in strlen >= N.
* How bad that is depends on the code - if you are checking the size
* before putting it in a buffer, then it's bad.
* To me it is logic in the assert and so I say BAD
*/
/* 4 */
assert(!*(s+strlen(s)));
/*
* First of that's just silly code.
* If that comes to my code review you'll be removing or rewriting
* it - strlen relies on the NUL, so how can it fail?
* It is logic in the assert - If NDEBUG is set you'll keep going
* even if the condition is not met. How bad that is?
*/
/* 5 */
assert(atol(s));
/*
* Whoa. If NDEBUG is set and s = "Hello" we still keep going...
* What is atol("Hello") ?
*/
printf("%ld\n", 100000000/atol(s));
free(s);
return 0;
}
int f(char *s)
{
/* 6 */
assert(s!=NULL);
/*
* Again if NDEBUG is defined the check disappears and so if s = NULL
* then you dereference a NULL pointer which is undefined behavior
*/
return !*s;
我希望此答案通過努力查看斷言示例的有意義用法來提供您的斷言的替代視圖。 否則,我同意譴責大多數問題的答案。
斷言用於驗證假設,即斷言它們是正確的。
認為一個斷言是
單獨查看斷言示例:
assert(false)
次數比我想象的要多。 這至少意味着“我盲目地認為運行時執行永遠不會在這里結束”。 但是非常奇怪,因此需要大量的(通常是缺失的)注釋說明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.