1

我正在构建一个程序,它读取一个充满单词的巨大标准输入。我想将输入分成最多 100 个字符的字符串。所以这是我的代码。

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

static char* string = "\0";

void getChar(char new){
    if (strcmp(string,"\0") == 0){
        free(string);
        string = (char *) malloc(sizeof(char));
        if (string == NULL){
            exit(EXIT_FAILURE);
        }
        string[0] = new;
    } else {
        char* newString = (char*) realloc(string, sizeof(string)+sizeof(char));
        if (newString == NULL){
            exit(EXIT_FAILURE);
        }
        string = newString;
        string[strlen(string)]=new;
    }
    if (strlen(string) > 100){
        printf("%s\n",string);
        dosomething(string);
        string = "\0";
    }
}

void getInput(){
    int temp;
    while((temp = fgetc(stdin)) != EOF){
        getChar((char) temp);
    }
}

int main(int argc, char *argv[]){
    getInput();
}

编译并执行代码后,我立即收到一条错误消息:

*** glibc detected *** ./sort: realloc(): invalid next size: 0x08f02008 //ofc this address always changes

在以后的版本中,我将通过 \n 过滤大于 100 个字符的字符串被忽略。

4

1 回答 1

3

sizeof(string)实际上告诉你string 它本身的大小(指针,因为这就是string它),而不是它指向的东西的长度。您需要自己跟踪字符串的长度,方法是使用strlen(这意味着它必须始终具有终止的零字节)或使用单独的长度变量。

还有很多其他的错误。您的第一个free(string)发生在string您分配的空间之前,这是致命的。

于 2013-05-16T02:59:09.503 回答