我可以跟踪动态内存吗?
can i track dynamic memory?
在许多情况下,我们在函数中动态声明指针,有时我们不想在函数返回时释放该内存,因为我们以后需要这些内存。
可以返回该动态指针,然后释放它。我找到了追踪那段记忆的方法。这是一件好事吗?
#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)
相关文章:
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 对具有动态分配的内存和析构函数的类对象的引用
- 以下代码执行哪种内存分配(动态或静态)?
- 开放 CV 中的动态内存分配,用于视频处理
- 调用析构函数以释放动态分配的内存
- 为什么类和 main() 函数中也有动态内存分配
- 将静态内存更改为动态C++
- 在没有动态内存的世界中,我是否需要虚拟析构函数?
- 在运行时为动态分配的内存输入值
- c++ 动态内存 堆栈中的分配
- 释放动态分配的内存时是否需要执行此额外步骤
- 动态分配字符数组的内存
- 销毁C++中动态分配的内存(数组对象)
- 给定特定内存地址的数组的动态内存分配
- 释放动态内存时C++错误
- 对内存动态分配的类不使用"*"的逻辑
- 如果我将内存动态分配给静态变量,我应该释放它还是会自动释放它
- 给定内存地址的内存动态初始化
- 删除指针分配的内存(动态数组)