我可以跟踪动态内存吗?

can i track dynamic memory?

本文关键字:内存 动态 跟踪 我可以      更新时间:2023-10-16

在许多情况下,我们在函数中动态声明指针,有时我们不想在函数返回时释放该内存,因为我们以后需要这些内存。

可以返回该动态指针,然后释放它。我找到了追踪那段记忆的方法。这是一件好事吗?

#include <iostream>
int foo()
{
    int* pInt = new int(77);
    int x = (int)pInt;
    std::cout << std::hex << x << std::endl; // 3831d8
    return x;
}

int main()
{
    int* pLostMem = (int*)foo();
    std::cout <<  pLostMem << std::endl; // 003831D8
    std::cout << std::dec << *pLostMem << std::endl; // 77 
    if(pLostMem)
    {
        delete pLostMem;
        pLostMem = NULL;
    }
    std::cout << std::endl;
    return 0;
}

您的问题并不完全清楚,但如果您只是想将cout语句添加到代码中以显示指针的值,则可以在不转换为int的情况下做到这一点。指针可以打印得很好:

#include <iostream>
int *foo()
{
  int* pInt = new int(77);
  std::cout << pInt << std::endl; // pointers can be output just fine
  return pInt;
}
int main()
{
  int* pLostMem = foo();
  std::cout << pLostMem << std::endl; // e.g. 0x16c2010
  std::cout << *pLostMem << std::endl; // 77
  delete pLostMem;
  pLostMem = NULL;
  std::cout << std::endl;
  return 0;
}

您也不需要在删除前检查if (pLostMem==NULL)