如果您glibc
在 iOS 上使用 GNU GCC 编译器,那么我相信您可以使用mprobe()
- 如果它失败,则内存块已损坏或堆栈内存块。
http://www.gnu.org/software/libc/manual/html_node/Heap-Consistency-Checking.html
使用 OS 可移植堆检测更新帖子:
new()
否则,您可以通过覆盖&来创建自己的堆内存管理器delete()
,记录所有堆内存分配/释放,然后添加自己的堆检测功能;示例如下:
// Untested pseudo code follows:
//
#include <mutex>
#include <map>
#include <iostream>
std::mutex g_i_mutex;
std::map<size_t, void*> heapList;
void main()
{
char var1[] = "Hello";
char *var2 = new char[5];
if (IsHeapBlock(&var1))
std::cout "var1 is allocated on the heap";
else
std::cout "var1 is allocated on the stack";
if (IsHeapBlock(var2))
std::cout "var2 is allocated on the heap";
else
std::cout "var2 is allocated on the stack";
delete [] var2;
}
// Register heap block and call then malloc(size)
void *operator new(size_t size)
{
std::lock_guard<std::mutex> lock(g_i_mutex);
void *blk = malloc(size);
heapList.Add((size_t)blk, blk);
return blk;
}
// Free memory block
void operator delete(void *p)
{
std::lock_guard<std::mutex> lock(g_i_mutex);
heapList.erase((size_t)p);
free(p);
}
// Returns True if p points to the start of a heap memory block or False if p
// is a Stack memory block or non-allocated memory
bool IsHeapBlock(void *p)
{
std::lock_guard<std::mutex> lock(g_i_mutex);
return heapList.find((size_t)p) != heapList.end();
}
void *operator new[] (size_t size)
{
return operator new(size);
}
void operator delete[] (void * p)
{
operator delete(p);
}