2014-03-06 60 views
0

我認爲我在重新分配令牌字符指針時遇到問題,請幫助。 我googged如何realloc,但我不知道這是否正確的方式來執行它,因爲我在運行我的程序時出現內存損壞錯誤。在C中重新分配內存

char* token = (char*)malloc(sizeof(char)); 
token[0] = '\0'; 
int c; 
do{   
    c = fgetc(fp); 
    if(isalnum(c)){ //add to char array 
     if(isalpha(c)) 
      c = tolower(c); 
     if(token[0] == '\0'){ 
      token[0] = (char)c; 
      token[1] = '\0'; 
     } 
     else{ 
      token = (char*)realloc(token, strlen(token)+2); 
      int len = strlen(token); 
      token[len] = (char)c; 
      token[len+1] = '\0'; 
     } 
    } 
    else{ //token 
     if(token[0] != '\0'){ //add token 
      struct token* newtoken = (struct token*)malloc(sizeof(struct token)); 
      newtoken->token = (char*)malloc(strlen(token)*sizeof(char)); 
      strcpy(newtoken->token, token); 
      newtoken->records = NULL; 
      struct record* newrecord = (struct record*)malloc(sizeof(struct record)); 
      newrecord->fileName = (char*)malloc(strlen(fileName)*sizeof(char)); 
      strcpy(newrecord->fileName, fileName); 
      newrecord->freq = 1; 
      tokens = (struct token*)addToken(tokens, newtoken, newrecord); 
     } 
     token[0] = '\0'; 
    } 
    if(feof(fp)) 
     break; 
}while(1); 
+0

您的第一個malloc只分配1個字符的空間。我想你至少需要2個字符。 –

+0

一個明顯的問題:你需要在'strcpy'之前分配'strlen(s)+ 1',因爲'strlen'不包含nul-terminator字符。 'malloc'之前你也不需要那些混亂的演員陣容。 –

+0

'char * token =(char *)malloc(sizeof(char));'你確定這是正確的嗎? sizeof(char)總是** 1 **,所以你會通過訪問'token [1]'...造成一些麻煩...... – Naytzyrhc

回答

1

您寫道:

char* token = (char*)malloc(sizeof(char)); 

更清楚地表述爲char *token = malloc(1);,這種分配1個字節。

但後來你去:

token[0] = (char)c; 
token[1] = '\0'; 

其寫入2個字節爲1字節分配。這是一個緩衝區溢出,可能是您的內存損壞的原因。你可以通過兩個字節的malloc來解決這個問題。

你以後也覆蓋你的緩衝區:

newtoken->token = (char*)malloc(strlen(token)*sizeof(char)); 
strcpy(newtoken->token, token); 

更改爲:

newtoken->token = malloc(strlen(token) + 1); 
strcpy(newtoken->token, token); 

通知我的版本比你如何有較少的疣太,所以它更容易閱讀,因此更容易被發現如果有任何錯誤。

之後strcpy之後也有同樣的問題。