簡體   English   中英

在C中重新分配內存

[英]Reallocating memory in C

我認為我在重新分配令牌字符指針時遇到問題,請幫忙。 我搜索了如何重新分配,但是我不確定這是否是正確的方法,因為在運行程序時出現MEMORY CORRUPTION錯誤。

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);

你寫了:

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

更清楚地表示為char *token = malloc(1); ,這會分配1個字節。

但是然后您去:

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

將2個字節寫入1個字節的分配中。 這是緩沖區溢出,可能是內存損壞的原因。 您可以通過分配兩個字節開始來解決此問題。

您稍后還會覆蓋緩沖區:

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

改成:

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

請注意,我的版本疣也比您的疣少,因此它更易於閱讀,因此在發現任何錯誤時也更容易發現。

之后的下一個strcpy也有相同的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM