2014-09-12 28 views
0

當* customer_num爲NULL時,下列宏會導致段錯誤傳遞。使用類似函數的宏來檢查是否定義了變量

#define SAVE(a,b,c) if(a){stchar(a,b,c);} 

在宏中有一種方法,我可以檢查是否定義了一個,如果不是,那麼只需使用NULL。 宏如果我只是使用NULL,如下所示。

SAVE(NULL,buf,16); 


1)save_cust(NULL); 
2)save_cust(char **customer_number,..etc); 
3)SAVE(*customer_number,buf,16); //causes seg fault since it *customer_number is undefined 
+3

你是什麼意思的「定義」? – Medinoc 2014-09-12 19:35:54

+2

如果你沒有聲明**你正在嘗試使用的變量,你的編譯器會吐出一個錯誤。你所做的只有在'a!= 0'時纔會生效。這是你所說的「定義」的意思嗎? – DevNull 2014-09-12 19:38:29

+0

按定義我的意思是它是NULL。如果customer_number爲NULL,那麼* customer_number也不應該爲NULL? – caaruiz 2014-09-12 19:53:39

回答

0

鑑於這種宏觀

#define SAVE(a,b,c) if(a){stchar(a,b,c);} 

和下面的調用

SAVE(*customer_number,buf,16); 

從預處理器的輸出是

if (*customer_number){stchar(*customer_number,buf,16);} 

結果是,你不檢查是否customer_number是NULL,但是您正在檢查*customer_number是否爲NULL。當爲NULL時,檢查*customer_number會導致seg_fault。

一個解決問題的方法是定義宏作爲

#define SAVE(a,b,c) if(a){stchar(*a,b,c);} 

,然後調用宏作爲

SAVE(customer_number,buf,16); 

經進一步審查,我認爲宏觀你正在尋找因爲是

#define SAVE(a,b,c) if(a && *a){stchar(*a,b,c);} 

如果實際上是一個指向指針的指針,那麼您需要首先驗證不爲NULL,然後驗證*customer_number不爲NULL。

相關問題