我有一個文件指針,在調用fread之前是有效的,之後是NULL,我真的很想知道爲什麼。爲什麼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的,並不表示我做錯什麼要麼...
我我喜歡認爲我很擅長處理返回值,確保指針是有效的,等等,但是這個讓我難住。
你肯定'FREAD(file_page,的sizeof(爲size_t),...'? – Jack
一號線447要傳遞的參數'read_page'順序錯誤 – shf301
如果Valgrind是不是撿什麼東西在這裏,然後valgrind是錯誤的你使用哪個操作系統? – Sebivor