Function Call Stack in C++ - 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

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.

Related

Switch off Memory Leak Detection in boost.Test

I'm currently using boost.Test and I'm wondering if it might be possible to switch off the Memory Leak Detection, if one compiles in DEBUG Mode.
I don't want to use the command line parameter switch --detect_memory_leak=0. I'm looking for a kind of #define parameter, that switches off the memory leak detection feature in DEBUG mode.
It would be also suitable for me to switch off the memory detection feature by defining a certain compiler switch. I'm currently using Microsoft Visual Studio 2010.
#define BOOST_TEST_DETECT_MEMORY_LEAK 0 // Preprocesser switch I'm looking for!
#define BOOST_TEST_MODULE MyUnitTest
#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_SUITE(MySuite);
BOOST_AUTO_TEST_CASE(MyUnitTest) {
/// Following code has a memory leak
/// ....
}
BOOST_AUTO_TEST_SUITE_END()
Just found out that possibly the best way to turn off the detection of memory leaks is to include the following code snippet into one's tests.
#include <boost/test/debug.hpp>
struct GlobalFixture {
GlobalFixture() {
boost::debug::detect_memory_leaks(false);
}
~GlobalFixture() { }
};
BOOST_GLOBAL_FIXTURE(GlobalFixture);
Still, I was not able to switch off and to switch on the detection of memory leaks for single tests.
You can directly set the environment variable BOOST_TEST_DETECT_MEMORY_LEAK to 0 or use putenv :
#include <cstdlib>
//...
BOOST_AUTO_TEST_CASE(MyUnitTest) {
putenv("BOOST_TEST_DETECT_MEMORY_LEAK=0");
//...
}
Edit
As you're using visual studio 2010, you can try _putenv or _wputenv :
#include <stdlib.h>
//...
BOOST_AUTO_TEST_CASE(MyUnitTest) {
_putenv("BOOST_TEST_DETECT_MEMORY_LEAK=0");
//...
}
Otherwise, I found a function detect_memory_leaks in the Boost documentation but it seems to be only available on recent boost version.
_CrtSetDbgFlag(0);
is the only thing that mostly worked for me. Leak messages came out, but not enough to make me wait.
Here's some code detailing everything I tried:
struct GlobalFixture
{
GlobalFixture()
{
// This doesn't seem to do anything
// boost::debug::detect_memory_leaks(false);
// This either
//_putenv("BOOST_TEST_DETECT_MEMORY_LEAK=0");
// This total hack also does nothing
// using namespace boost::unit_test::runtime_config;
// const_cast<boost::runtime::arguments_store&>(argument_store()).set(btrt_detect_mem_leaks, 0);
// This gets rid of most of the messages
_CrtSetDbgFlag(0);
}
};
Why not use the _DEBUG macro ?
#ifdef _DEBUG
#define BOOST_TEST_DETECT_MEMORY_LEAK 0
#endif

Visual Studio 2010 debugger points to wrong line

The debugger in Visual Studio 2010 is recently pointing at the wrong lines and/or skipping lines and I have no idea why this is. This is a CUDA project and only happens in CUDA files. I've noticed the following:
It always happens at the same part of the program.
The lines it points to are always the same, i.e. not random.
Putting extra code after the culprit lines changes which lines it points to.
It only happens in .cu-files. Moving the code to a .cpp-file does not recreate the problem.
What I have tried:
Clean and rebuilt the solution.
Install SP1 for MSVC10 and do all possible updates via Windows Updates
Set the compiler to not use optimizations in debug mode for both C/C++ and CUDA C/C++
Manually delete all created files and then rebuild from the solution folder.
Deleting the folder C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
Recreating the solution only using the source files.
Disabling my extensions.
I've managed to reduce the code to the following which might reproduce the problem. Mind that this code has to be inside a .cu-file and most probably needs to be compiled with the cuda compiler for C/C++. Including boost is not really necessary, but this example does show what problems I'm having. A shorter example is at the back.
#include <boost/numeric/ublas/matrix.hpp>
using boost::numeric::ublas::matrix;
struct foo {
foo() : mat(NULL) {}
matrix<float>* mat;
};
bool func(foo *data) {
bool status; // <- skipped line
status = false;
if (status) {
std::cout << "test\n";
return (status); // <- error reported here
}
int size = data->mat->size1(); // instead of here
return status;
}
int main(int args, char* argv[]) {
func(NULL); // force error by passing NULL pointer
return 0;
}
Does anyone have any idea how to solve this or how this could be happening? It's pretty annoying having to debug this way.
Shorter example only showing the skipping lines. No external libraries necessary.
bool func() {
bool status; // <- skipped line
status = false;
return status;
}
int main(int args, char* argv[]) {
func();
return 0;
}
Since the program only contains CPU instructions and variable declarations of types that have no construction contain no instructions, the debugger will not stop there. It just executes instructions and then uses the debugging information that the compiler provided to find the relevant line of source code.

Not finding function using GetProcAddress() C++ VBexpress 13

Okay so I'm coming dangerously close to a repost here but my situation is a little bit different than the numerous other posters about this function. I am interfacing with a DLL that was written way back in the day and all I have is the file. I don't have a .lib file so I'm using the LoadLibrary and GetProcessAddress functions. I followed the tutorial on the MSDN website to get the basic structure. the DLL is located in the project folder. it compiles. at run time, I am getting a numerical value for "hinstLib" so I'm assuming the DLL was found. I am getting a null value for "ProcAdd" variable. Other posters had there issues resolved by putting extern C in the DLL functions but I don't really have that option. not to mention, to my knowledge this DLL was written in plain C. I do have an interface document and am quite sure I have the function name correct (replaced with a generic example for these purposes). I honestly didn't run anything past the ProcAdd assignment because it came out NULL. Any thoughts as to why this is giving me a 0 value for the function assignment would be great appreciated. Note: unfortunately due to various reasons I can't upload the DLL.
#include <iostream>
#include "stdafx.h"
#include "Windows.h"
#include <stdio.h>
typedef int(__cdecl *MYPROC)(LPWSTR);
using namespace std;
int main()
{
HINSTANCE hinstLib;
MYPROC ProcAdd;
BOOL fFreeResult, fRunTimeLinkSuccess = FALSE;
hinstLib = LoadLibrary(TEXT("dllName.dll"));
if (hinstLib != NULL)
{
ProcAdd = (MYPROC) GetProcAddress(hinstLib, "funcName");
// If the function address is valid, call the function.
if (NULL != ProcAdd)
{
fRunTimeLinkSuccess = TRUE;
//(ProcAdd) (L"Message sent to the DLL function\n");
}
// Free the DLL module.
fFreeResult = FreeLibrary(hinstLib);
}
// If unable to call the DLL function, use an alternative.
if (! fRunTimeLinkSuccess)
printf("Message printed from executable\n");
return 0;
}
Compilers usually mangle function names, then a function named funcName may appear inside the DLL with a name funcName#16 , for example... It depends on calling convention and are important for a function to be called properly. For __cdecl calling convention you probably need _funcName :-) .

GDB: sync breakpoints with modified code

Some breakpoints are set during debugging, then saved with save breakpoints bps.
Code is modified by adding a few lines in the middle on the file.
When gdb is started again and source bps is done, those breakpoints, which are above first occurrence of code modification are ok, rest of them are relatively moved.
Is there a way to do some smart synchronization of breakpoints with modified file?
Is there a way to do some smart synchronization of breakpoints with
modified file?
This depends on how you are setting breakpoints. You can try to set them independently of line numbers, for example at function name:
(gdb) b main
This way breakpoint location is independent on line numbers and synchronizes automatically with modified file.
You can add the breakpoints in the source code by doing int 3:
#include <stdio.h>
#define __DEBUG
#ifdef __DEBUG
#define __breakpoint__() __asm__ __volatile__("int $3\n")
#else
#define __breakpoint__()
#endif
int main(int argc, char **argv) {
const char *p = "Hello world!";
__breakpoint__();
printf("'%s'\n", p);
return 0;
}

GDB does not break on some lines of code when using multiple source files

I have a program that I'd like to debug by setting a breakpoint in a non-default constructor, but the breakpoint I set is never hit. Below is an example program where this problem comes up. There is no problem hitting breakpoints set in the main function, but any breakpoints set in the Domain.cpp file are ignored:
Main.cpp:
#include <iostream>
#include "Domain.h"
int main()
{
Domain y;
std::cout << y.x << std::endl; // <- No problem setting breakpoint here
return 0;
}
Domain.cpp:
#include "Domain.h"
Domain::Domain()
{
x = 4; // <- A breakpoint here is skipped
}
Domain.h:
#ifndef DOMAIN_H_
#define DOMAIN_H_
class Domain
{
public:
int x;
public:
Domain();
};
#endif /* DOMAIN_H_ */
However, the problem does not exist if I put everything into a single file:
Main2.cpp:
#include <iostream>
int main()
{
class Domain
{
public:
int x;
Domain()
{
x = 4; // <- No problem setting breakpoint here now!
};
};
Domain y;
std::cout << y.x << std::endl;
return 0;
}
Why is this the case? How can I change this so that I'm able to set breakpoints when I use multiple files?
I can confirm that the breakpoints aren't working both when I run the debugger manually in a terminal and when I run it through Eclipse CDT, where I get the same error discussed in this question which was apparently never answered:
Why does Eclipse CDT ignore breakpoints?
I am using:
Eclipse Kepler
Mac OSX 10.8.4
gdb 6.3.5 (Apple version)
gcc 4.2.1 with -O0 and -g3 flags
Please be patient with me. I'm still learning the ropes.
You are likely hitting this GDB bug.
This bug has long been fixed, but your version of GDB is very old (and Apple is unlikely to update it).
This is a very interesting anomaly that I would like to explore further, but I suspect it's related to Eclipse's default GCC settings. Many super basic functions like these get optimized out when they hit the compiler. (one time I tried to track a simple for loop, but the viable was removed entirely on GCC's highest optimization settings)