函数strlen入参空指针引发的段错误

背景

  在工作中调试sqlite3相关代码的时候,调用printf()打印sqlite3_exec()的执行日志;因为sqlite3_exec()保存日志的参数传入时为NULL,且没有执行错误,所以再传入printf()时仍然为NULL;如果判断日志不为空时才打印,则无段错误。

分析

Core was generated by `./hello.cgi'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  strlen () at ../sysdeps/x86_64/strlen.S:106
106    ../sysdeps/x86_64/strlen.S: 没有那个文件或目录.
(gdb) bt
#0  strlen () at ../sysdeps/x86_64/strlen.S:106
#1  0x00007f2c160d4fa2 in _IO_puts (str=0x0) at ioputs.c:35
#2  0x000055b86da5ba4b in sqlite_mytest () at hello.cc:239
#3  0x000055b86da5b1f9 in main () at hello.cc:67
(gdb) quit

根据gdb调试信息,定位到 :

  #0 strlen () at ../sysdeps/x86_64/strlen.S:106

错误产生的原因,就是在hello.c的239行调用printf()时入参为NULL,printf()内部调用最终将其传递到strlen()

关于printf()入参NULL的分析,可以再作了解。

总结

  对prinf()的入参作非空判断

  strlen()在glibc内部没有作非空判断,不可传NULL。

 
原文地址:https://www.cnblogs.com/orejia/p/12059047.html