今天在寫代碼時遇到一個問題並於在一個函數傳遞參數時連續調用inet_ntoa時出現的,下面是問題的類比代碼:
16 char ip_addr1[]= "192.168.1.20"; 17 char ip_addr2[]= "192.168.1.40"; 18 19 int main(int argc,char**argv) 20 { 21 struct in_addr addr1, addr2; 22 char ip1[16]={0}, ip2[16]={0}; 23 24 bzero(&addr1,sizeof(structin_addr)); 25 bzero(&addr2,sizeof(structin_addr)); 26 27 inet_aton(ip_addr1,&addr1); 28 inet_aton(ip_addr2,&addr2); 29 30 printf("ip address 1:%s\tip address 2:%s\n", inet_ntoa(addr1),
inet_ntoa(addr2)); 31 32 return 0; 33 }
|
按理說,輸出的結果應該是:
ip address 1:192.168.1.20 ip address 2:192.168.1.40
可是結果是:
ip address 1:192.168.1.20 ip address 2:192.168.1.20
當時遇到這個問題的時候沒太注意,可以費了我好長時候才去去關注它,這裡只是猜出inet_ntoa的實現方法,並沒有去閱讀他的實現代碼,先看下面的例子:
5 //str must end with null, and its size must be less 1024 bytes 6 char* alltoupper(constchar* str){ 7 #define BUF_LEN 1024 8 static char buf[BUF_LEN]; 9 int idx=0; 10 if(!str)return NULL; 11 if(strlen(str)>=BUF_LEN)return NULL; 12 while(*str!= '\0'){ 13 if(idx<BUF_LEN){ 14 buf[idx++]= toupper(*str++); 15 } 16 } 17 buf[idx]='\0'; 18 return buf; 19 #undef BUF_LEN 20 } 21 22 int main(int argc,char** argv){ 23 printf("%s\t%s\n",alltoupper("hello,world!"),alltoupper("That's what it is!")); 24 return 0; 25 }
|
這個函數輸出的也和我們"想象"的不一樣,如下:
HELLO,WORLD! HELLO,WORLD!
是不是和上面的一樣的?
其實這裡面的道理很簡單,返從函數返回指標,要麼是靜態變數,要麼是malloc等分配的動態變數,要麼是傳遞進去的記憶體指標。而這裡的三種情況中,第二種情況,個人認為是最好不要用的,記憶體應該誰分配誰釋放,但是另一個函數strdup確是使用了第二種方法。
對於返回函數內部的靜態變數雖然出了函數範圍,其變數名無效了,但其分配的空間還在,再次進入同一個函數時,不會再次對靜態變數進行初始化的,所以在一個函數傳遞參數的時候,同時調用兩次這類函數,對同一個靜態變數,實際上是後者覆蓋了前者,兩都都是指向同一個內容,所以會出現上面兩段代碼的結果。
由於沒有真正的看過inet_ntoa函數的實現,這裡只是過行猜測,不過這個道理是存在的,以後有時間再閱讀一下其實現吧。