如何在_crtsetallochook中获取和使用文件名和行号? [英] How to get and use filename and linenumber inside _crtsetallochook?

查看:63
本文介绍了如何在_crtsetallochook中获取和使用文件名和行号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在_crtsetallochook中获取和使用文件名和行号?

How to get and use filename and linenumber inside _crtsetallochook?

int _cdecl customallochook (int type, void *pdata, size_t size, int use, long request, const unsigned char *file, int line)
{
//how to use *file and line here???
}

推荐答案

这是一个钩子函数,因为它由C运行时系统的_CrtSetAllocHook使用.当使用_DEBUG编译分配时,这些参数将包含分配所源自的文件名和行号.

您可能需要使用它们来跟踪内存泄漏. MFC在此基础上实现了泄漏检测机制,您自己的钩子函数可能想做类似的事情.这就是为什么这些事情通过的原因.如果不需要在挂钩函数中使用它们,只需忽略它们即可.
This is a hook function as it is used by _CrtSetAllocHook of the C runtime system. When you compile your allocation with _DEBUG, these parameters will contain the file name and line number on which the allocation originated from.

You might want to use them for tracking down memory leaks. MFC implements a leak detection mechanism on this basis and your own hook function might want to do something similar. That is why these things are passed. If you don''t need them in your hook function, just ignore them.


Check this[^] for some pre-defined macros.

HTH
Abhi


仅当源文件为
时,钩子才会接收文件名和行号 设置了"new"或malloc以使用
的调试版本 ``新操作员'',然后malloc并将此信息传递给他们.

这可以通过以下方式完成:

1)通常在预编译的头文件中:

The hook receives the file name and line number only if the source file
that called ''new'' or malloc was set up to use the debug versions of
''operator new'' and malloc and pass them this information.

This can be done in the following way:

1) Usually in the precompiled header file:

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new(_NORMAL_BLOCK, THIS_FILE, __LINE__)



2)在每个带有内存分配的源文件的开头:



2) At the beginning of every source file with memory allocations:

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif



@ nv3-我猜你是说这个意思吗?即使这样做,我也无法在参数中接收文件名和行号.您能帮我详细地在_DEBUG之下进行此编译吗?你是对的,我需要它来防止内存泄漏.



@nv3 - I guess you mean this right? Even after doing this I am not able to recieve the filename and linenumber in the parameters. Can you please help me with this compilation under _DEBUG thing in detail. You are right i need it for memory leaks.


这篇关于如何在_crtsetallochook中获取和使用文件名和行号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆