gpt4 book ai didi

c - 文件指针为 0x0 但所有 NULL 检查失败

转载 作者:行者123 更新时间:2023-11-30 16:36:27 25 4
gpt4 key购买 nike

如果这是一个愚蠢的问题,我深表歉意,因为我是 C 语言新手。

我正在尝试用 C 语言处理文件列表。如果打开文件时 fopen() 返回 NULL,我会跳过它;否则继续下去是安全的。

问题是我所有的 NULL 检查都失败了。以下 if 语句均不会执行(另外,fopen() 也不应失败,因为我始终提供有效的文件路径...)。

编辑:有人要求我发布所有相关代码:就是这里,从 main() 开始:

int num_words_to_show;
int max_occurrances;

FILE* fp = NULL;
char*** freq_arr = NULL;
HashTable* table = make_hash_table();

num_words_to_show = 10;

/* Populate hash table from input. Exit if could not populate. */
if (!populate_table(table, fp, argc, argv, &num_words_to_show)) {
fprintf(stderr, "%s\n", USAGE_ERR);
return 1;
}

现在有问题的函数:

int populate_table(HashTable* table, 
FILE* fp,
int argc,
char* argv[],
int* num_words_to_show) {
int filename_index;

/* Description for input_is_valid():
If input is invalid, prints error messages and returns -1.
Else if no input file specified, return -2.
Otherwise, returns starting index of filenames and
sets variable determining how many values to show.
*/
filename_index = input_is_valid(argc, argv, num_words_to_show);

if (filename_index == -1) {
return 0;
}
else if (filename_index == -2) {
printf("%s\n", "Index is -2");
parse_words(table, NULL);
}
else {
/* Loop through all opened files. */
for (; filename_index < argc; ++filename_index) {
fp = fopen(argv[filename_index], "r");

if (!fp) { /* DOES NOT EXECUTE */
perror(argv[filename_index]);
continue;
}

if (fp == NULL) { /* DOES NOT EXECUTE */
printf("%s\n", "File is null");
continue;
}

if (fp == 0x0) { /* DOES NOT EXECUTE */
printf("Comparison to literal 0 failed.");
continue;
}

parse_words(table, fp); /* <-- Causes segfault as not expecting NULL for fp */
fclose(fp);
}
}

return 1;

最后一个条件的值是我直接从 GDB 获取的,但仍然失败。这是 GDB 输出:

Breakpoint 1, populate_table (table=0x603010, fp=0x0, argc=2, argv=0x7fffffffe338, num_words_to_show=0x7fffffffe234) at fw.c:80
80 if (!fp) {
(gdb) s
Breakpoint 2, populate_table (table=0x603010, fp=0x0, argc=2, argv=0x7fffffffe338, num_words_to_show=0x7fffffffe234) at fw.c:85
85 if (fp == NULL) {
(gdb) s
Breakpoint 3, populate_table (table=0x603010, fp=0x0, argc=2, argv=0x7fffffffe338, num_words_to_show=0x7fffffffe234) at fw.c:90
90 if (fp == 0x0) {
(gdb) s
94 parse_words(table, fp);
(gdb) p fp
$1 = (FILE *) 0x0

如有任何提示,我们将不胜感激。谢谢!

最佳答案

当 fp 为 null 时,您的第一个比较 if (!fp) 为 true,并执行继续continue 的意思是“开始下一个循环周期”,因此 CPU 会直接返回到 for,并开始下一次迭代。其他 if 永远不会到达。

关于c - 文件指针为 0x0 但所有 NULL 检查失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48482912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com