On macOS/Darwin, yes you can.
Pass your pointer to malloc_zone_from_ptr(…)
; if it gives you NULL
back, it wasn't allocated with any variant of malloc
/calloc
/etc.
This is the same mechanism that's used spit out a “*** error for object %p: pointer being freed was not allocated” and SIGABRT when you try to free()
a non-malloc'd pointer. See Darwin's malloc.c
Here's some test code:
#include <malloc/malloc.h>
…
int *mallocAllocated = (int *)malloc(16);
int *newAllocated = new int[16];
int stackAllocated[16];
printf("mallocAllocated allocated with malloc: %s\n",
(malloc_zone_from_ptr(mallocAllocated) != NULL) ? "yes" : "no");
printf("newAllocated allocated with malloc: %s\n",
(malloc_zone_from_ptr(newAllocated) != NULL) ? "yes" : "no");
printf("stackAllocated allocated with malloc: %s\n",
(malloc_zone_from_ptr(stackAllocated) != NULL) ? "yes" : "no");
free(mallocAllocated);
free(newAllocated);
free(stackAllocated); // aborts with SIGABRT here
outputs:
mallocAllocated allocated with malloc: yes
newAllocated allocated with malloc: yes
stackAllocated allocated with malloc: no
Caveat: Is this safe across all Darwin platforms and builds, and all types of memory allocation? No idea. All I know is what the source code and man malloc_zone_from_ptr
says.
Why would you want to do this specifically on a macOS/«Apple»OS/Darwin system? Well, if you're playing around with stack-allocating Objective-C objects and you want to make sure you don't call [super dealloc]
into NSObject's implementation, that would be one esoteric use-case.