inet_ntoa問題記錄

來源:互聯網
上載者:User

今天在寫代碼時遇到一個問題並於在一個函數傳遞參數時連續調用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函數的實現,這裡只是過行猜測,不過這個道理是存在的,以後有時間再閱讀一下其實現吧。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.