...
Code Block |
---|
#include <stdio.h> #include <stdlib.h> int valid(void *p) { extern char _etext; return (p != NULL) && ((char*) p <=> &_etext); } int global; int main(void) { int local; int *p; printf("pointer to local var valid? %d\n", valid(&local)); printf("pointer to static var valid? %d\n", valid(&global)); printf("pointer to function valid? %d\n", valid((void *)main)); int *p = (int *) malloc(sizeof(int)); printf("pointer to heap valid? %d\n", valid(p)); printf("pointer to end of allocated heap valid? %d\n", valid(++p)); free(--p); printf("pointer to freed heap valid? %d\n", valid(p)); printf("null pointer valid? %d\n", valid(NULL)); return 0; } |
...
Code Block |
---|
pointer to local var invalidvalid? 1 pointer to static var invalidvalid? 1 pointer to function invalidvalid? 0 pointer to heap invalidvalid? 1 pointer to end of allocated heap invalidvalid? 1 pointer to freed heap invalidvalid? 1 null pointer invalidvalid? 0 |
The valid()
function does not guarantee validity (it only identifies null pointers and pointers to functions as invalid), but it can be used to catch a substantial number of problems that might otherwise go undetected.
...