简体   繁体   English

readdir 调用的段错误

[英]segfault on readdir call

I'm trying to perform a readdir(): here is the code:我正在尝试执行 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);

I've got a segfault on the while ((dirp = readdir(dp)) != NULL) and the program do not cross the else if statement.我在while ((dirp = readdir(dp)) != NULL)上遇到了段错误,并且程序没有跨越 else if 语句。

Valgrind output:瓦尔格林德 output:

==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

Any idea?任何的想法?

if (dp = opendir("saves") == NULL)

You missed the parens around the assignment here which you need because == has higher precedence than = .你错过了你需要的赋值周围的括号,因为==的优先级高于=

You've assigned the result of the comparison to dp which is certainly not a valid pointer.您已将比较结果分配给dp ,这肯定不是有效指针。

You need:你需要:

if ((dp = opendir("saves")) == NULL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM