我有代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
size_t foo_len (const char *s)
{
return strlen (s);
}
int main (int argc, char *argv[])
{
const char *a = NULL;
printf ("size of a = %d\n", foo_len (a));
exit (0);
}
Run Code Online (Sandbox Code Playgroud)
用调试符号编译它:
$ gcc example.c -g -o example
Run Code Online (Sandbox Code Playgroud)
并在GDB中运行
$ gdb ./example
user@ubuntu:~$ gdb ./example
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./example...done.
Run Code Online (Sandbox Code Playgroud)
GDB运行
(gdb) run
Starting program: ./example
Run Code Online (Sandbox Code Playgroud)
我应该得到类似的东西
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400527 in foo_len (s=0x0) at example.c:8
8 return strlen (s);
Run Code Online (Sandbox Code Playgroud)
但得到了:
Program received signal SIGSEGV, Segmentation fault.
strlen () at ../sysdeps/x86_64/strlen.S:106
106 ../sysdeps/x86_64/strlen.S: No such file or directory.
Run Code Online (Sandbox Code Playgroud)
哪里有问题?
维基百科中的示例不正确?
问题是你要传递NULL给它strlen(),这会导致未定义的行为,从而导致崩溃.您似乎期望在调用之前在您的代码中发生未定义的行为,这没有任何意义.
如果你有标准库的源代码,你将能够看到它发生的源代码行; 它看起来像是strlen()用汇编写的.当然,您可以通过要求gdb使用该disassemble命令反汇编代码来查看说明.
这个:
printf ("size of a = %d\n", foo_len (a));
Run Code Online (Sandbox Code Playgroud)
是错的,你不能合法打印一个size_t好像是一个int; 不是.您应该使用%zu打印类型的值size_t:
printf("length of a = %zu\n", foo_len(a));
Run Code Online (Sandbox Code Playgroud)
另外,谈论字符串的"大小"(而不是它的长度)有点令人困惑.