我正在和指針做鬥爭:(我試着做一個類似於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]時表示:無效的指針。
你能告訴我錯誤在哪裏嗎?我完全失去了,任何幫助將是有用的
請格式化你的代碼下一次說明在編輯頁面 – 2010-12-06 19:55:59