2010-10-31 38 views
0

在follwoing代碼,用libxml的庫:錯誤在一個簡單的C代碼(指針)

key = xmlNodeListGetString(doc, cur3->xmlChildrenNode, 1); 
       if (flag == 1) 
       { 
         image2 = key; 
         printf("the image 2 is %s \n", image2); 
         flag = 2; 
       } 
       if(flag == 0) 
       { 
         image1 = key; 
         printf("the image 1 is %s \n", image1); 
         flag = 1; 
       } 
        //printf("SRC of the file is: %s\n", key); 

       xmlFree(key); 
      printf("the image 1 is %s \n", image1); 

兩個printf的是給我不同的輸出。

輸出是:

the image 1 is 1.png 
the image 1 is 0p� g 
the image 2 is 2.png 
the image 1 is 0p� g 

回答

6

後,行image1 = key,image1key指向相同的內存區域。

我想xmlFree(key);改變這個內存區域。 如果您希望此字符串的內容存活到xmlFree,您應該在取消分配指針之前考慮使用函數strcpy

+0

謝謝你的工作就像一個魅力。 – w2lame 2010-10-31 13:00:52

0

您還沒有提到什麼是image1key?我猜是指針(因爲標籤和因爲函數名+ c標籤)。如果是這樣,問題是調用printf之前調用xmlFree(key); - keyimage1都指向相同的內存位置(如果是指針),所以這是問題所在。 printf之後輸入xmlFre(key)

你也應該在第二個if(前面加else

-1

據我可以從一小段無證代碼中看到它,它並沒有真正意義的調用xmlfree(),它轉換對於

但真正的原因VAR image1的改變例如1.png到0P克是因爲此搜索是關鍵,然後通過調用xmlfree(key)的更新參考。

+0

是的,謝謝了這個問題。 – w2lame 2010-10-31 12:24:27