【发布时间】: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 orvoid *in general.并且不要在取消引用运算符之后添加空格;编写可读的代码。