3

For debugging reasons I am trying to print the name of the function that made an illegal memory access (out of range for example).

I have written a SIGSEGV signal handler to print the Instruction Pointer (IP) and the faulted memory address, but I was not able to create a method such that I can get the function name and not the IP.

Is there a way to modify the signature of the signal handler to pass the __ FUNCTION __ variable as an argument or is there another method to do this?

Note: The program is written in C and I trying to do this in a Linux environment.

Florin Avram
  • 167
  • 1
  • 7
  • 1
    What would be the use for that? You cannot even rely on getting a segfault for undefined behaviour. During development use a debugger, possibly post-mortem on a core-dump. At run-time, try graceful termination and that's it. And `__FUNCTION__` is not a variable, but a **pre**processor macro. – too honest for this site Feb 22 '16 at 15:23
  • Why not use a debugging tool such as [Valgrind](http://valgrind.org/) which will help you with just about all things memory debugging related. – Some programmer dude Feb 22 '16 at 15:25
  • You need to get the stack trace(backtrace) of the thread. Check this. http://stackoverflow.com/questions/6402160/getting-a-backtrace-of-other-thread – Umamahesh P Feb 22 '16 at 15:33
  • More details here: http://stackoverflow.com/questions/105659/how-can-one-grab-a-stack-trace-in-c – Umamahesh P Feb 22 '16 at 15:35
  • Why not just running you program with gdb ? – Jabberwocky Feb 22 '16 at 15:36
  • 1
    @Olaf I am trying to trap every memory access made to a well defined heap allocated memory by all the functions. I thought that **__FUNCTION__** is a variable because that is what the gcc documentation states. (https://gcc.gnu.org/onlinedocs/gcc/Function-Names.html) – Florin Avram Feb 22 '16 at 15:40
  • @MichaelWalz I want to run the program an get a log-file with the functions that accessed heap memory location. – Florin Avram Feb 22 '16 at 15:42
  • @UmamaheshP Thank you for the links. They seem to be what I need. – Florin Avram Feb 22 '16 at 15:44
  • @FlorinAvram: Sorry, I was misslead by the all-uppercase. Why not use the standard `__func__`? Never use an extension if there is a standard way already. – too honest for this site Feb 22 '16 at 16:05

1 Answers1

3

You can use backtrace and backtrace_symbols_fd to print the function names with call stack.

Check the man pages for backtrace and backtrace_symbols or backtrace_symbols_fd.

An example is here:

http://man7.org/linux/man-pages/man3/backtrace.3.html

alk
  • 69,737
  • 10
  • 105
  • 255
Umamahesh P
  • 1,224
  • 10
  • 14