Scrambling Memory

There are many problems dealing with pointers in C. One source of bugs is dereferencing a pointer that has been freed.

These bugs are quite difficult to debug. The program will continue to work for some time, with the freed region being read and written to normally. Then, that region will be allocated, and overwritten. A very large number of instructions can elapse the point memory is freed and the point the program crashes.

Further, the change that triggers the bug is usually caused by changing the memory allocation pattern. This means that the last change could be completely unrelated to either the point the memory was freed, or to where the program crashes.

In fact, in some environments, the act of running the program under the debugger can disturb allocation enough to allow the program to run correctly.

To make this class of bugs easier to isolate, scramble the memory as soon as it is freed. Thus:


	#define SCRAMBLE_VALUE_XFREE	0xfc
	#define xfree(_t, _p)	\
	  	( memset((_p), SCRAMBLE_VALUE_XFREE, sizeof(_t)), \
		  free(_p))
	#define xnfree(_t, _n, _p)	\
	  	( memset((_p), SCRAMBLE_VALUE_XFREE, (_n)*sizeof(_t)), \
		  free(_p))

If SCRAMBLE_XFREE is enabled, before a memory block is freed, we scramble it; basically, write 0xfc to each byte of the memory block. This, in general, makes bugs surface earlier.

Consider the following code sequence:


	destroy_int_stack(stack);
	/* this calls free(struct int_stack, stack) */
	x = top_int_stack(stack);
	/* this dereferences stack->vals */

Without memory scrambling this code fragment would work. With memory scrambling, stack->vals would be set to 0xfcfcfcfc. When this value is dereferenced, it will cause the program to crash (on most systems).

On your system, pick the SCRAMBLE_VALUE_XFREE value so that:


Next Prev Main Top Feedback