【问题标题】:Passing file content into memory is faulty将文件内容传递到内存是错误的
【发布时间】:2018-01-03 10:32:00
【问题描述】:

我想知道为什么虽然我认为我会适当地调用函数来加载, 似乎 fread 无法正确读入我的内存块,因此会造成分段错误[在加载函数中]!请指出正确的方法

代码的link

#include <math.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

bool load(FILE* file, char** content, size_t* length);

int main()
{
    // opens file
    FILE * file = fopen("test.txt", "r");

    // initialises variables 
    char* content;
    size_t length;

    // sending arguments to load function
    bool receive = load(file, &content, &length);

    // debugging content
    printf("values of content: %s\n", content);

    // debugs length

    printf("values of content: %zu\n", length);

    // closes file
    fclose(file);

    // for success
    return 0;
}

bool load(FILE* file, char** content, size_t* length)
{

    {

    // proof checking for the existence of file
    if (file == NULL)
        {
            return false;
        }

    // perusing to end of file   
    fseek(file, 0, SEEK_END);

    // for approximation of size of file    
    size_t len = ftell(file);

    // returns cursor to beginning of file  
    fseek(file, 0, SEEK_SET);

    // apportions memory on heap for content of file
    * content = (char *) malloc (len + 1);

    // memory error checking

    if(*content == NULL)
    {
        printf("It's unfortunate\n");

    }
    // to read into content     
    fread(* content, sizeof(char), len, file);

    // null terminates content
    (* content)[len] = 0;

    // debugs content    
    printf(" content contains %s\n", * content);

    // debugs length    
    * length = len;

    printf(" length is %d\n", * length);

    // if success 
    return true;

    }

    // if fail 
    return false;
}

谢谢

【问题讨论】:

  • 请直接在问题中发布Minimal, Complete, and Verifiable example,而不是链接到它。虽然该链接确实包含您的代码,但将来可能会过时。
  • 虽然我不得不说这个链接很好,一个真正的 IDE,我可以在其中查看代码并调试它等等 - 我知道它会消失等等,但即使这样也很容易回答
  • 嗯,最明显的错误是如果load 返回false,您只需继续。而且您也永远不会检查 fopen 是否有效
  • DWon't cast the result of malloc & friends or void * in general.并且不要在取消引用运算符之后添加空格;编写可读的代码。

标签: c function file


【解决方案1】:

您需要检查文件是否打开正常

  FILE * file = fopen("test.txt", "r");
  if(file == NULL)
  {
      perror("failed to open file: ");
      exit(1);
  }

其次,您的加载函数返回 false 失败,但您不检查它。做

 bool receive = load(file, &content, &length);
 if(!receive)
 {
     fprintf(stderr, "failed to read file");
     exit(1);
 }

在你做的负载

  if(*content == NULL)
    {
        printf("It's unfortunate\n");

    }

但继续进行。你应该这样做

 if(*content == NULL)
    {
        printf("It's unfortunate\n");
        return false;
    }

一般来说,您不会检查您调用的任何函数的返回,fseek,ftell,fread,....当您的程序失败时您不应该感到惊讶。是的,这是一个无聊的过程,但在 C 领域就是这样

【讨论】:

    猜你喜欢
    • 2018-08-08
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多