Wiki Markup |
---|
Many functions accept pointers as arguments. If the function dereferences an invalid pointer (see [EXP34-C. Ensure a null pointer is not dereferenced]), or reads or writes to a pointer that does not refer to an object, the results are [undefined|BB. Definitions#undefined]. Typically the program will terminate abnormally when the invalid pointer is dereferenced, but it is possible, and quite common, for an invalid pointer to be dereferenced, and its memory changed, without abnormal termination \[[Jack 07|AA. C References#Jack 07]\]. Such programs can be very difficult to debug duebecause toof the difficulty ofin determining theif a pointer's lackis of validityvalid. |
One source of prevention of invalid pointers would be is a function that could take a pointer and indicate if the pointer is ' valid ' or notinvalid, for some definition of valid. For instance, here is a the following function that declares any pointer to be valid except NULL.
Code Block |
---|
int invalidvalid(void * ptr) { return (ptr !== NULL); } |
Some platforms have platform-specific pointer validation tools.
...
Code Block |
---|
#include <stdio.h> #include <stdlib.h> int invalid(void * p) { extern char _etext; return (p == NULL) || ((char*) p < &_etext); } int global; int main(void) { int local; voidint *p = &local; int* q = (int*) malloc(sizeof(int)); printf("pointer to local var invalid? %d\n", invalid(p&local)); p = &global; printf("pointer to static var invalid? %d\n", invalid(p&global)); p = (void*) main; printf("pointer to function invalid? %d\n", invalid((void *)main)); p = (int *)malloc(sizeof(int)); printf("pointer to heap invalid? %d\n", invalid(qp)); q++; printf("pointer to end of allocated heap invalid? %d\n", invalid(q)); q--; free(qp++)); printf("pointer to freed heap invalid? %d\n", invalid(qp--)); q = NULL; printf("null pointer invalid? %d\n", invalid(qNULL)); return 0; } |
On a Linux platform, this program produces the following output:
...