簡體   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