understanding stack trace of a segmentation fault

hari picture hari · Jul 17, 2011 · Viewed 10k times · Source

I am doing an snprintf and getting a seg fault.

when I loaded the core file on gdb like this: gdb my_executable core ; and did bt to get the backtrace, I got following:

Program terminated with signal 11, Segmentation fault.
#0  0x88207fc2 in memcpy () from /usr/lib/libc.so.6
(gdb) bt
#0  0x88207fc2 in memcpy () from /usr/lib/libc.so.6
#1  0x88205eb6 in __sfvwrite () from /usr/lib/libc.so.6
#2  0x881fbc95 in strchr () from /usr/lib/libc.so.6
#3  0xbfbe6c14 in ?? ()
#4  0xbfbe69d8 in ?? ()
#5  0x881ed91e in localeconv () from /usr/lib/libc.so.6
#6  0x881fec05 in __vfprintf () from /usr/lib/libc.so.6
#7  0x881f7d80 in snprintf () from /usr/lib/libc.so.6  
#8  0x08052b64 in my_function (files=0xbfbed710, filename=<value optimized out>) at myfile.c:1102
#9  0x08053bfb in main (argc=4, argv=0xbfbedd90) at myfile.c:225

I see such stack many times in case of seg fault but never understood correctly.

Just looking the calls in trace, can we tell what is going wrong?

NOTE: Please do not ask for more code. My motive is simply understand what the stack-trace like this means - irrespective of code. I see that on the top "memcpy" is failing. I want to understand when that can happen in this situation.

Answer

cnicutar picture cnicutar · Jul 17, 2011

You function does something at myfile.c:1102. This in turn tricks the standard library into illegally accessing memory. The operating system notices and slaps your program with sigsegv.

Common reasons, (as seen on Stackoverflow :)) ) are:

  • Writing to read-only memory
  • Using uninitialized pointers
  • Accessing memory past the end of an allocated block

The long list of functions shows you who did it. So:

  • my_function called snprintf
  • which called __vfprintf
  • ...