在C语言中重新分配内存

在C语言中重新分配内存,c,realloc,C,Realloc,我想我在重新定位令牌字符指针时遇到问题,请帮助。 我绞尽脑汁研究了如何realloc,但我不确定这是否是正确的方法,因为我在运行程序时遇到了内存损坏错误 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))

我想我在重新定位令牌字符指针时遇到问题,请帮助。 我绞尽脑汁研究了如何realloc,但我不确定这是否是正确的方法,因为我在运行程序时遇到了内存损坏错误

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字节分配。这是缓冲区溢出,可能是内存损坏的原因。您可以通过malloc`ing两个字节来解决这个问题

您还可以稍后覆盖缓冲区:

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

newtoken->token = malloc( strlen(token) + 1 );
strcpy(newtoken->token, token);
请注意,我的版本比你的版本有更少的缺点,因此更容易阅读,因此更容易发现是否有任何错误


之后的下一个strcpy也有同样的问题。

您的第一个malloc只为1个字符分配空间。我认为您至少需要2个字符。一个明显的问题是:您需要在
strpy
之前分配
strlen+1
,因为
strlen
不包含nul终止符。您也不需要在
malloc
char*token=(char*)malloc(sizeof(char))之前进行这些混乱的强制转换您确定这是正确的吗?sizeof(char)总是1,因此访问
令牌[1]
会造成一些麻烦。..@Naytzyrhc:
sizeof char
被定义为1,但是
令牌[1]
无论大小都是无效的。我建议您先分配一个内存块,当内存块用完时再分配一个新的块。一次分配几个字节/realloc是无效的。