Reputation: 18175
I have code :
#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);
}
Compile it with debug symbols:
$ gcc example.c -g -o example
And run in 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.
GDB run
(gdb) run
Starting program: ./example
I was expected to get something like
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400527 in foo_len (s=0x0) at example.c:8
8 return strlen (s);
But got :
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.
Where is problem?
Sample in wikipedia is not correct ?
Upvotes: 1
Views: 8641
Reputation: 399703
The problem is that you're passing NULL
to strlen()
, which causes undefined behavior, and thus a crash. You seem to be expecting the undefined behavior to happen in your code, before the call, which makes no sense.
If you had the source code for the standard library you would be able to see the source line where it happened; it looks like your strlen()
was written in assembly. You can of course view the instructions anyway, by asking gdb to disassemble the code using the disassemble
command.
Also this:
printf ("size of a = %d\n", foo_len (a));
is wrong, you can't legally print a size_t
as if it's an int
; it's not. You should use %zu
to print values of type size_t
:
printf("length of a = %zu\n", foo_len(a));
Also, talking about the "size" of a string (and not its length) is a bit confusing.
Upvotes: 8
Reputation: 36317
Well, the segmentation fault does happen in strlen and not in your function, so the fact that you see it happen there is correct.
Use your distributions install tool to get the debug symbols for your C library (glibc, if in doubt), and try again.
Upvotes: 0
Reputation: 78903
Your error happens inside strlen
. To see the full call stack in gdb use the command bt
for backtrace.
Upvotes: 2