【问题标题】:Invalid address on realloc [duplicate]realloc 上的地址无效 [重复]
【发布时间】:2013-05-16 02:57:50
【问题描述】:

我正在构建一个程序,它可以读取一个充满单词的巨型标准输入。我想将输入分成最多 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 个字符的字符串被忽略。

【问题讨论】:

  • 建议:在 C 程序中避免使用像 new 这样的 C++ 关键字。

标签: c malloc realloc


【解决方案1】:

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

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

【讨论】:

  • @TorhanBartel:只有当你总是放置一个终止零字节时,你才没有。例如,您执行string[0] = new; -- 但它只存储一个字符,它不存储字符串。所以你不能在上面使用strlen
  • 好的,所以我需要一个用于字符串的内存地址...比如 main() 中的 malloc?
  • 我需要设置 \0 个字符
  • 如果将其存储为字符串,则可以使用strlen 查找其长度(减去终止的零字节)。
  • 如果你能记住 sizeof 实际上是在编译时解析的,那么记住使用 strlen 会容易得多,因为在编译时你不会知道字符串的长度。
猜你喜欢
  • 2017-12-25
  • 2011-02-25
  • 2012-10-31
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
  • 2013-11-29
  • 2018-06-13
  • 2021-12-25
相关资源
最近更新 更多