GNU C 库中的 opendir( ) sigsegv
我在 x86-64 架构的 Linux 上使用 Eclipse。当向 opendir() 传递空指针时,我在调用时遇到段错误。
char* directory = NULL;
/*
* ...
* Get directory from the command line. If not given, directory will be NULL.
* ...
*/
DIR* dir = opendir( directory ); // Seg fault here with null pointer. Instruction: cmpb $0x0,(%rdi)
我可以在调用 opendir() 之前放置一个简单的保护线来检查空指针。然而,我觉得奇怪的是 opendir() 方法的第一行不会是这样的:
if( dir == NULL )
return NULL;
我只是在这里迂腐,还是我错过了一些东西?
顺便说一句,我很好奇为什么错误发生在 cmpb 操作码处?此外,Eclipse 在信号窗格中没有显示任何有关段错误的信息。
提前致谢, 安德鲁
I'm using Eclipse on Linux on an x86-64 arch. I'm getting a seg fault at the call to opendir() when passing it a null pointer.
char* directory = NULL;
/*
* ...
* Get directory from the command line. If not given, directory will be NULL.
* ...
*/
DIR* dir = opendir( directory ); // Seg fault here with null pointer. Instruction: cmpb $0x0,(%rdi)
I could put a simple guard line before the call to opendir() to check for a null pointer. However, I find it strange that the first line of the opendir() method wouldn't be something like:
if( dir == NULL )
return NULL;
Am I just being pedantic here, or am I missing something?
As an aside, I'm curious why the fault occurs at the cmpb opcode? Also, Eclipse shows nothing about the seg fault in the signals pane.
Thanks in advance,
Andrew
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个设计决策 - 标准库和 POSIX 中的许多函数都按照您描述的方式运行。错误检查是调用者的责任。尝试使用空指针调用
strlen()
- 它的行为方式可能相同。就您而言,失败的指令似乎是有道理的。 RDI 可能是空指针,并且尝试取消引用该空指针会导致分段错误。所讨论的 cmpb 指令似乎是检测传入字符串的空终止符的循环的一部分。
It's a design decision - many functions in the standard library and POSIX behave the way you describe. Error checking is the caller's responsibility. Try calling
strlen()
with a null pointer - it will likely behave the same way.In your case, the failing instruction seems to make sense. RDI is probably the null pointer, and attempting to dereference that null pointer causes the segmentation fault. The
cmpb
instruction in question appears to be part of a loop detecting for the null terminator of the passed-in string.