【问题标题】:Calling fopen gives malloc error at runtime调用 fopen 在运行时给出 malloc 错误
【发布时间】:2015-09-30 11:29:57
【问题描述】:

我正在使用此函数将文件的内容读入字符串

void readFile2String(char **string, char location[]){
    FILE *fileList;
    int size;
    char *temp;
    char command[1024];


    if((fileList=fopen(location,"r")) == NULL){
        perror(" Error opening list of directories: ");
        exit(2);
    }

    fseek(fileList,0,SEEK_END);
    size = ftell(fileList);
    rewind(fileList);
    temp = malloc((size+1)*(sizeof(char)));
    fread(temp,sizeof(char),size,fileList);
    temp[size]=0;   // Terminate string with 0
    *string = temp;
    fclose(fileList);
}

我正在使用该字符串进行进一步操作。我称这个函数为

char *temp;
readFile2String(&temp, fileName);

我成功获取了字符串中的文件内容。但是当稍后我尝试再次使用 fopen 时,我在运行时收到 malloc 错误。我已经尝试在这个程序中注释掉对这个函数的调用,之后,我可以根据需要多次使用 fopen。我的功能有什么问题?

谢谢。

【问题讨论】:

  • malloc 的所有内容都必须通过free 归还。你基本上是在泄漏内存。也许不是马上,而是稍后的某个地方。
  • 您没有包含您遇到的确切错误,因此很难说明它无法按预期工作的原因。
  • ftell() 返回一个long 而不是int,所以size 的声明应该是long size;...这对于一个非常大的文件来说可能是个大问题。
  • 注意:sizeof(char) 永远不会产生与1 不同的任何东西。没必要拿。如果您想让malloc 更便携(无论出于何种原因),请使用sizeof(*temp)
  • ftell 返回一个long int。这可能与int 的宽度相同,但你不应该依赖它。

标签: c string file malloc


【解决方案1】:
  1. “fopen()”不会导致内存损坏'“free()”也不会失败(如果实际上您没有执行 free()。

  2. 您正在验证“fopen()”的返回 - 很好。问:为什么不同时检查 fseek()、ftell()、rewind() 和 fread() 的错误情况?

  3. 我的猜测是temp[size]=0; 可能是导致内存损坏的罪魁祸首。或者fread()。知道“大小”肯定会有用。

建议:

仔细检查调试器,并验证您的 I/O 返回的每一步

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 2018-02-02
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    相关资源
    最近更新 更多