我有以下代码:
#include "stdafx.h"
#include <process.h>
#include <iostream>
#include <Windows.h>
#include "dbghelp.h"
using namespace std;
int LogStackTrace()
{
void *stack[1024];
HANDLE process = GetCurrentProcess();
SymInitialize(process, NULL, TRUE);
WORD numberOfFrames = CaptureStackBackTrace(0, 1000, stack, NULL);
SYMBOL_INFO *symbol = (SYMBOL_INFO *)malloc(sizeof(SYMBOL_INFO));
symbol->MaxNameLen = 1024;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
IMAGEHLP_LINE *line = (IMAGEHLP_LINE *)malloc(sizeof(IMAGEHLP_LINE));
line->SizeOfStruct = sizeof(IMAGEHLP_LINE);
printf("Caught exception ");
for (int i = 0; i < numberOfFrames; i++)
{
SymFromAddr(process, (DWORD64)(stack[i]), NULL, symbol);
SymGetLineFromAddr(process, (DWORD)(stack[i]), NULL, line);
printf("at %s in %s, address 0x%0X\n", symbol->Name, line->FileName, symbol->Address);
}
return 0;
}
void function2()
{
int a = 0;
int b = 0;
throw new exception("Expected exception.");
}
void function1()
{
int a = 0;
function2();
}
void function0()
{
function1();
}
static void threadFunction(void *param)
{
try
{
function0();
}
catch (...)
{
LogStackTrace();
}
}
int _tmain(int argc, _TCHAR* argv[])
{
try
{
_beginthread(threadFunction, 0, NULL);
}
catch (...)
{
LogStackTrace();
}
printf("Press any key to exit.\n");
cin.get();
return 0;
}
问题在于,此行总是出错:printf("at %s in %s, address 0x%0X\n", symbol->Name, line->FileName, symbol->Address);
原因是因为line的FileName似乎是NULL。实际上,整个线路结构搞砸了。我正在尝试编写一个应用程序来显示错误的堆栈跟踪。但那是为什么呢?它不应该使用上面的代码吗? PS我作为一个简单的MSVC ++控制台应用程序对Win32进行了编译。
答案 0 :(得分:2)
SYMBOL_INFO *symbol = (SYMBOL_INFO *)malloc(sizeof(SYMBOL_INFO));
symbol->MaxNameLen = 1024;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
The documentation for SizeOfStruct
州:
结构的大小,以字节为单位。必须将此成员设置为sizeof(SYMBOL_INFO)。 请注意,数据的总大小是SizeOfStruct +(MaxNameLen - 1)* sizeof(TCHAR)。减去1的原因是名称中的第一个字符的大小是结构。
强调我的。您必须分配至少sizeof(SYMBOL_INFO) + MaxNameLen + 1
个字节的存储空间。您只分配sizeof(SYMBOL_INFO)
个字节。
答案 1 :(得分:2)
您的代码存在同样的问题(Windows 7 64b,Unicode 32位版本,VS2012 Express)
修正了:
DWORD dwDisplacement;
SymGetLineFromAddr(process, (DWORD)(stack[i]), &dwDisplacement, line);