From: Ivan Maidanski Date: Thu, 29 Dec 2011 12:12:37 +0000 (+0400) Subject: Add GC_is_heap_ptr() to GC API X-Git-Tag: gc7_3alpha2~242 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=dcf6f521380c9e686956e8df7afb1e04d088091b;p=gc Add GC_is_heap_ptr() to GC API * include/gc.h (GC_is_heap_ptr): New API function declaration. * misc.c (GC_is_heap_ptr): New function. * tests/test.c (run_one_test): Add GC_is_heap_ptr tests. --- diff --git a/include/gc.h b/include/gc.h index a7fd4490..a6eac699 100644 --- a/include/gc.h +++ b/include/gc.h @@ -410,6 +410,12 @@ GC_API void GC_CALL GC_end_stubborn_change(void *); /* GC_free. */ GC_API void * GC_CALL GC_base(void * /* displaced_pointer */); +/* Return TRUE if and only if the argument points to somewhere in GC */ +/* heap. Primary use is as a fast alternative to GC_base to check */ +/* whether the pointed object is allocated by GC or not. It is assumed */ +/* that the collector is already initialized. */ +GC_API int GC_CALL GC_is_heap_ptr(const void *); + /* Given a pointer to the base of an object, return its size in bytes. */ /* The returned size may be slightly larger than what was originally */ /* requested. */ diff --git a/misc.c b/misc.c index 18cc44d5..63262e1e 100644 --- a/misc.c +++ b/misc.c @@ -391,6 +391,15 @@ GC_API void * GC_CALL GC_base(void * p) return((void *)r); } +/* Return TRUE if and only if p points to somewhere in GC heap. */ +GC_API int GC_CALL GC_is_heap_ptr(const void *p) +{ + bottom_index *bi; + + GC_ASSERT(GC_is_initialized); + GET_BI(p, bi); + return HDR_FROM_BI(bi, p) != 0; +} /* Return the size of an object, given a pointer to its base. */ /* (For small objects this also happens to work from interior pointers, */ diff --git a/tests/test.c b/tests/test.c index 9802f34e..e51f74cf 100644 --- a/tests/test.c +++ b/tests/test.c @@ -1105,6 +1105,18 @@ void run_one_test(void) GC_printf("GC_base(heap ptr) produced incorrect result\n"); FAIL; } + if (!GC_is_heap_ptr(x)) { + GC_printf("GC_is_heap_ptr(heap_ptr) produced incorrect result\n"); + FAIL; + } + if (GC_is_heap_ptr(&x)) { + GC_printf("GC_is_heap_ptr(&local_var) produced incorrect result\n"); + FAIL; + } + if (GC_is_heap_ptr(&fail_count) || GC_is_heap_ptr(NULL)) { + GC_printf("GC_is_heap_ptr(&global_var) produced incorrect result\n"); + FAIL; + } (void)GC_PRE_INCR(x, 0); (void)GC_POST_INCR(x); (void)GC_POST_DECR(x);