为什么对fread的调用会将我的文件指针设置为null?

时间:2013-05-18 15:14:44

标签: c file-io fread

我有一个文件指针,在调用fread之前有效,之后是NULL,我真的很想知道原因。

以下是相关代码:

244 // open the file for reading
245 clo->heap_file = open_file(heap_path, "rb");

443 // allocate memory to read a page from the file
444 file_page = safe_malloc(clo->page_size);

446 // read a page in to memory from the file
447 read_page(file_page, clo);

void *
safe_malloc(size_t size)
{
   void * mem_block = NULL;

   mem_block = calloc(1, size);

   if (mem_block == NULL) {
      fprintf(stderr, "ERROR: safe_malloc() failed to allocate memory.\n");
      exit(EXIT_FAILURE);
   }

   return (mem_block);
}

FILE *
open_file(char * file_name, char * file_mode)
{
    FILE * fp;
    char * err_msg = ((strcmp(file_mode, "rb") == 0)
          ? "File not found"
          : "File could not be created");

    fp = fopen(file_name, file_mode);

    /* Print an appropriate error message and exit if open failed */
    if (fp == NULL) {
       fprintf(stderr, "%s: %s\n", err_msg, file_name);
       exit(EXIT_FAILURE);
    }

    return fp;
}

void
read_page(clo_t * clo, void * file_page)
{
   fread(file_page, sizeof(size_t), clo->page_size, clo->heap_file);

   if (ferror(clo->heap_file)) {
      fprintf(stderr, "ERROR: could not read heap file!\n\n");
      free(file_page);
      destroy_clo(clo);
      exit(EXIT_FAILURE);
   }
}

GDB追踪:

(gdb) p clo->heap_file
$1 = (FILE *) 0x603070
(gdb) s
read_page (clo=0x6032d0, file_page=0x603010) at dbquery.c:331
331        fread(file_page, clo->page_size, 1, clo->heap_file);
(gdb) s
333        if (ferror(clo->heap_file)) {
(gdb) p clo->heap_file
$2 = (FILE *) 0x0

Valgrind并没有表明我做错了......

我想我觉得我擅长处理返回值,确保指针有效等等,但是这个让我感到难过。

1 个答案:

答案 0 :(得分:2)

你有2个问题,

  1. 根据功能定义将447 read_page(file_page, clo);更改为447 read_page(clo, file_page);

  2. fread(file_page, sizeof(size_t), clo->page_size, clo->heap_file);更改为fread(file_page, 1, clo->page_size, clo->heap_file);。不要将sizeof(size_t)用作fread的第二个参数。

    您的来电将尝试读取sizeof(size_t) * clo->page_size字节,这比您为file_page分配的1 * clo->page_size更多。