How to check pointer points to heap or memory stack on iOS?

This is an analogue of another question , anyway, I'm looking for a specific way for the platform to do this if it exists on iOS.

Developing for the Apple platform means that a non-Apple toolkit is usually not applicable. Therefore, I want to find my own way of the platform. Since a simple google search gave me this ( heap ) , I'm sure there is an API function too.

I am only looking for this to validate the debug assembly to detect a case of deleting an object allocated by the stack. Therefore, it is enough to know where the address is indicated - a stack or a heap. Therefore, performance, version compatibility, the internal API, or any quality problems do not matter. (maybe simulator testing may also be an option). But I think that this is not so difficult operation if the stack is completely separated from the heap.

I noted C ++, but an API in any other language is also great if it is applicable to C ++.

+4
source share
1 answer

If you use the GNU GCC compiler and glibc on iOS, I suggest that you can use mprobe() - if it fails, then the memory block is either damaged or the stack memory block.

http://www.gnu.org/software/libc/manual/html_node/Heap-Consistency-Checking.html

Updated OS Heap Detection message:

Otherwise, you can create your own heap memory manager by overriding new() & delete() , write down all heap memory allocations / deallocations, then add your own heap detection function; example:

 // 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); } 
+1
source

Source: https://habr.com/ru/post/1493073/


All Articles