//打印堆栈
#include <stdarg.h>
#include <windows.h>
//#include <dbghelp.h>
#include <stdio.h>
#if _MSC_VER
#define snprintf _snprintf
#endif
#define STACK_INFO_LEN 1024
static int vsnprintf_s(char* buf, size_t len, const char* fmt, va_list arg)
{
return ::vsnprintf_s(buf, len, _TRUNCATE, fmt, arg);
}
static int vsnprintf_s(wchar_t* buf, size_t len, const wchar_t* fmt, va_list arg)
{
return ::_vsnwprintf_s(buf, len, _TRUNCATE, fmt, arg);
}
static int snprintf_s(char* buf, size_t len, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
int nRes = vsnprintf_s(buf, len, fmt, args);
va_end(args);
return nRes;
}
void ShowTraceStack(char* szBriefInfo)
{
static const int MAX_STACK_FRAMES = 12;
void* pStack[MAX_STACK_FRAMES];
static char szStackInfo[STACK_INFO_LEN * MAX_STACK_FRAMES];
static char szFrameInfo[STACK_INFO_LEN];
HANDLE process = GetCurrentProcess();
SymInitialize(process, NULL, TRUE);
WORD frames = CaptureStackBackTrace(0, MAX_STACK_FRAMES, pStack, NULL);
strcpy(szStackInfo, szBriefInfo == NULL ? "stack traceback:\n" : szBriefInfo);
strcat(szStackInfo, " ");
for (WORD i = 0; i < frames; ++i) {
DWORD64 address = (DWORD64)pStack[i];
DWORD64 displacementSym = 0;
char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)];
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
pSymbol->MaxNameLen = MAX_SYM_NAME;
DWORD displacementLine = 0;
IMAGEHLP_LINE64 line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE64);
if (SymFromAddr(process, address, &displacementSym, pSymbol) &&
SymGetLineFromAddr64(process, address, &displacementLine, &line))
{
snprintf_s(szFrameInfo, sizeof(szFrameInfo), "\t%s() at %s:%d(0x%x)\n",
pSymbol->Name, line.FileName, line.LineNumber, pSymbol->Address);
}
else
{
snprintf_s(szFrameInfo, sizeof(szFrameInfo), "\terror: %d\n", GetLastError());
}
strcat(szStackInfo, szFrameInfo);
}
MyLog(L"%s", CString(szStackInfo));//此处是你的日志函数
}
在什么情况下使用打印堆栈函数?
1.一个函数多次调用,调用地方不同,不能下断点,打印日志也看不出什么,打印堆栈可以看出。
2.分析崩溃。
缺点:文章来源:https://www.toymoban.com/news/detail-816940.html
1.看不到调用堆栈栈帧变量的值。只能看到调用堆栈函数。文章来源地址https://www.toymoban.com/news/detail-816940.html
到了这里,关于Windows打印堆栈的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!