2010-12-06 22 views
1

我正在和指針做鬥爭:(我試着做一個類似於argv返回的東西的函數,我的意思是,我希望它把一個命令分成一些字符串,每一個(即:order [0],order [1])。在動態矩陣中處理​​指針的問題

我想爲任意數量的單詞做所以我使用dinamic內存。爲了順序分開我使用strtok的順序,它的工作是正確的問題是處理指針:

在結果**我保留內存與realloc指針指向每個單詞,因此,當有令牌我做以下:

  • 我增加resul
  • 大小我保留存儲器的指針到令牌
  • 我ASIGN令牌

(文本停止降價freakout)

#include <string.h> 
#include <stdio.h> 
#include <stdlib.h> 

int main(int argc, char *argv[]){ 
    char linea[] = "send UDP 4500 50"; 
    char **resul=NULL; 
    int numTokens,conta2; 
    char *sep=" ";//character which divides the orders 
    int conta=0; //counter of the number of tokens found 
    char *saveptr,*token; 

    for(token=strtok_r(linea,sep,&saveptr); token!=NULL; token=strtok_r(NULL,sep,&saveptr)){ 
     printf("token: %s\n",token); 
     printf("size: %i\n",(conta+1)*sizeof(char*)); 
     resul = (char **)realloc(resul,(conta+1)*sizeof(char*)); //Increase the size for the array of pointers 

     resul[conta]= malloc(sizeof(char*)); //Reserve size for the pointer 
     resul[conta]=token; //Asign word to the pointer 
     conta++; 
    } 
    //Print the results 
    for(conta2=0;conta2<conta;conta2++) 
     printf("resul: \"%s\"\n",resul[conta2]); 
    //free memory 
    for(conta2=0;conta2<conta;conta2++){ 
     printf("liberando: %i\n",conta2); 
     free(resul[conta2]); 
    } 
    free(resul); 
    return(0); 
} 

輸出爲:

$ ./lectura_consola 
token: send 
size: 4 
token: UDP 
size: 8 
token: 4500 
size: 12 
token: 50 
size: 16 
resul: "send" 
resul: "UDP" 
resul: "4500" 
resul: "50" 
liberando: 0 
*** glibc detected *** ./lectura_consola: free(): invalid pointer: 0xbffb7f1b *** 

如果我爲了看到在存儲器中的故障,在免費用的valgrind運行(resul [0])的步驟發生的是:

liberando: 0 
==8372== Invalid free()/delete/delete[] 
==8372== at 0x40257ED: free (vg_replace_malloc.c:366) 
==8372== by 0x80489FA: main (lectura_consola.c:92) 
==8372== Address 0xbee8e28b is on thread 1's stack 

利用該代碼,該程序保存和正確打印的話,但在釋放內存的時刻它會發生什麼,當它試圖釋放resul [0]時表示:無效的指針。

你能告訴我錯誤在哪裏嗎?我完全失去了,任何幫助將是有用的

+0

請格式化你的代碼下一次說明在編輯頁面 – 2010-12-06 19:55:59

回答

2

這裏的問題是,你試圖釋放你沒有分配的內存。你在你的第一個環有這樣的代碼:

resul[conta]= malloc(sizeof(char*)); //Reserve size for the pointer 
resul[conta]=token; //Asign word to the pointer 

第二條語句覆蓋從第一條語句,這樣,當你調用free(resul[conta]),你要釋放結果token(這是一個指針到一個字符串)而不是您分配的指針。

在任何情況下,您都不需要第一條語句。您的realloc調用爲指針數組保留空間。對malloc的這個調用只是分配sizeof(char*)字節而沒有好的效果(即浪費內存)。而且由於這個價值只是被覆蓋了,你最終會泄露這個內存。

只需刪除對malloc的調用,並且您的代碼應該可以工作。

+1

我剛剛說了,但是請注意,以這種方式使用realloc並不安全,就好像realloc失敗了,然後原始數組被泄露。 – OrangeDog 2010-12-06 20:05:44

0

至於我記得strtok的不分配內存只是insterts \ 0標記之間,這意味着你自由只讀程序存儲器 - 發送UDP 4500 50" 就是這樣