readdir 调用的段错误
segfault on readdir call
我正在尝试执行 readdir():这是代码:
DIR *dp;
struct dirent *dirp;
if (dp = opendir("saves") == NULL) {
my_printf("Cannot open saves directory.\n");
return 84;
} else if ((dirp = readdir(dp)) == NULL) {
printf("hello\n");
} else
while ((dirp = readdir(dp)) != NULL)
printf("%s\n", dirp->d_name);
我在 while ((dirp = readdir(dp)) != NULL)
上遇到段错误,程序没有通过 else if 语句。
Valgrind 输出:
==4398== Invalid read of size 4
==4398== at 0x4AB99C3: readdir (in /usr/lib/libc-2.33.so)
==4398== by 0x10C047: save_map (save_button.c:23)
==4398== by 0x10C0ED: save_button_event (save_button.c:36)
==4398== by 0x10BBA7: check_close (window_process.c:52)
==4398== by 0x10A44F: main (my_world.c:19)
==4398== Address 0x4 is not stack'd, malloc'd or (recently) free'd
有什么想法吗?
if (dp = opendir("saves") == NULL)
你错过了你需要的作业周围的括号,因为 ==
的优先级高于 =
。
您已将比较结果分配给 dp
,这肯定不是有效指针。
你需要:
if ((dp = opendir("saves")) == NULL)
我正在尝试执行 readdir():这是代码:
DIR *dp;
struct dirent *dirp;
if (dp = opendir("saves") == NULL) {
my_printf("Cannot open saves directory.\n");
return 84;
} else if ((dirp = readdir(dp)) == NULL) {
printf("hello\n");
} else
while ((dirp = readdir(dp)) != NULL)
printf("%s\n", dirp->d_name);
我在 while ((dirp = readdir(dp)) != NULL)
上遇到段错误,程序没有通过 else if 语句。
Valgrind 输出:
==4398== Invalid read of size 4
==4398== at 0x4AB99C3: readdir (in /usr/lib/libc-2.33.so)
==4398== by 0x10C047: save_map (save_button.c:23)
==4398== by 0x10C0ED: save_button_event (save_button.c:36)
==4398== by 0x10BBA7: check_close (window_process.c:52)
==4398== by 0x10A44F: main (my_world.c:19)
==4398== Address 0x4 is not stack'd, malloc'd or (recently) free'd
有什么想法吗?
if (dp = opendir("saves") == NULL)
你错过了你需要的作业周围的括号,因为 ==
的优先级高于 =
。
您已将比较结果分配给 dp
,这肯定不是有效指针。
你需要:
if ((dp = opendir("saves")) == NULL)