繁体   English   中英

获取被调用函数的行号

[英]Gettin line number of the called function

请让我知道我是否可以做到?

我正在编写一个可以在 C++ 中跟踪内存分配和取消分配的库。 简而言之,我想看看我的应用程序是否没有任何内存泄漏。 这是我到目前为止所做的。

覆盖 new 和 delete 运算符,现在。 每当应用程序使用 new 时,我都计划存储在该调用中分配的地址和字节数。 同样,当对该地址调用删除时,我将从存储列表中删除它。 直到现在还好。 但我想存储调用“new”的文件名和行号。 我只能在被覆盖的 new 中做到这一点。 有没有办法在重写的函数中获取行号?


1    int main()
2    {
3       // Say, A is a structure
4        A *a = new A();
5        return 0;
6     }
7    void* operator new( size )
8    {
9        //
10       // store the line number and file name on line 4 ??? Can I do it?
11       return (malloc(size));
12   }
------------------------

从 C++20 开始,您可以使用std::source_location提供:

  • 线
  • 柱子
  • 文件名
  • 函数名

对于以前版本的 C++,传统上宏__LINE__给出了行号,但__FUNCTION____FILE__也非常有用,给出了封闭函数的 const char* 和文件名。

事实上, __FUNCTION__不是标准的,但有几个编译器支持。

不幸的是,这些宏只发挥了它们的价值。 因此,您不可能要求呼叫者。

您应该在任何使用new地方编写__LINE____FILE__宏。 :(。

最后我得到了这个论坛中一个类似线程的答案......下面的代码有效......让我们说,

class A
{
    public:
    char str[1000];
    A()
    {
        strcpy(str,"Default string");
    }
    A(const char* s)
    {
        strcpy(str,s);
    }
};

void * operator new (unsigned size, char const * file, int line)
{
    cout << "File = " << file << endl;
    cout << "Line = " << line << endl;
    return( malloc(size));
}
#define new new(__FILE__, __LINE__)
int main()
{
    A *a = new A("Leak");
    printf("%s",a->str);
    delete a;
    return 0;
}

我找到答案的相关帖子... 在 C++ 中重载 new 和 delete

您可以使用 studio dbx 运行时检查功能来识别 Solaris 下的内存泄漏 ( http://blogs.oracle.com/janitor/entry/runtime_memory_checking 。) libumem 也非常有用 ( http://blogs.oracle.com /pnayak/entry/finding_memory_leaks_within_solaris 。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM