Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Call Stack in C++

I have tried the following links, from StackOverflow and other sites,[I tried, but it didn't helped me, so i can't avoid duplicating]

StackWalk64 on Windows - Get symbol name

How do you make StackWalk64() work successfully on x64?

http://www.codeproject.com/KB/threads/StackWalker.aspx

http://jpassing.com/2008/03/12/walking-the-stack-of-the-current-thread/

How to Log Stack Frames with Windows x64 ...

But none of the Code worked for me.I'm new to Windows C++ environment and i can't get any of the above code to work.

I'm looking for a call stack format like,
FUNCTION_NAME_DEPTH_1 : _LINE_NUM__
FUNCTION_NAME_DEPTH_1 : _LINE_NUM__
FUNCTION_NAME_DEPTH_1 : _LINE_NUM__ ...

Just function name and line numbers.

My Environment:
Visual Studio 2010
SDK : v7.1
Windows 7 Pro SP1

It would be a lot simple if anyone post a header file,[there seems to be few available,but not working] which we can include in our cpp file and print the call stack with a call like 'PrintFunctionCallStack();' . BTW in Linux/Mac, it was a whole lot easier,i was able to get the call stack from backtrace and it was so simple that i did it myself in few mins. In Windows i've have been trying past two days, but no surprise at all.

Linux/Mac Stack Trace Code, i haven't yet demangled the symbol names.

#ifndef _STACKTRACE_H_
#define _STACKTRACE_H_

#include <stdio.h>
#include <stdlib.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <iostream>

static inline void PrintStackTrace()
{
        cout<<"##############################################\n";
        unsigned int maxStackCount = 63;
        void* addressList[maxStackCount+1];
        int addrLen = backtrace(addressList, sizeof(addressList) / sizeof(void*));
        if (addrLen == 0) {
            cout<<"Empty Stack, Probably Corrupted it seems ###\n";
            return;
        }
        char** symbolList = backtrace_symbols(addressList, addrLen);
        for (int i = 1; i < addrLen; i++) // Skipped First, 'i' begins with '1'
        {
                cout<<"###: "<<symbolList[i]<<":###\n";
        }
        free(symbolList);
        cout<<"##############################################\n";
}
#endif
like image 786
Zeus Avatar asked Nov 13 '22 03:11

Zeus


1 Answers

If your environment is Visual Studio, you can insert a Tracepoint and input

$CALLSTACK

in its edit box, after checking Print a message.

To do it, right-click on the line you want and select Breakpoint > Insert Breakpoint (or alternatively, insert a breakpoint clicking on the left of the editor line you want, then select When Hit).

Then you will see a detailed report in the Output window, having file name, line number and function name. It served me to successfully discovered some memory leaks.

like image 146
sergiol Avatar answered Nov 15 '22 05:11

sergiol