1

我有一个文件指针,它在调用 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 也没有表明我做错了什么......

我想我很擅长处理返回值,确保指针有效等,但这让我很难过。

4

1 回答 1

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

于 2013-05-18T15:31:01.780 回答