Getting a backtrace from running C code

Published on: 2006-9-12

Home | Archive

Getting a backtrace from running C code

2006-09-12T23:04:00

Came across two interesting GNU libc functions which helps us to get backtraces without using gdb. The backtrace function accepts an array of void*'s and fills it up with return addresses along the call chain - the total number of addresses stored is returned. The backtrace_symbols function accepts this array and returns an array of pointers to strings (function names). It seems you have to compile the code with the -rdynamic option to get proper function names.


fun1()
{
	int size, i;
	void *buf[100];
	char **fnames;

	size = backtrace(buf, 100);
	printf("size = %d\n", size);

	fnames = backtrace_symbols(buf, size);
	for(i = 0; i < size; i++)
		printf("%s\n", fnames[i]);
}

fun2()
{
	fun1();
}

main()
{
	fun2();
}