What happens if you free a pointer twice?


Levels of difficulty: / perform operation:

If you free a pointer, use it to allocate memory again, and free it again, of course it’s safe

If you free a pointer, the memory you freed might be reallocated. If that happens, you might get that pointer back. In this case, freeing the pointer twice is OK, but only because you’ve been lucky. The following example is silly, but safe:

#include <stdio.h>
#include <conio.h>
int main(int argc, char** argv) {
	char** new_argv1;
	char** new_argv2;
	new_argv1 = calloc(argc+1, sizeof(char*));
	free(new_argv1);
	/* freed once */
	new_argv2 = (char**) calloc(argc+1, sizeof(char*));
	if (new_argv1 == new_argv2) {
		/* new_argv1 accidentally points to freeable memory */
		free(new_argv1);
		/* freed twice */
	} else {
		free(new_argv2);
	}
	new_argv1 = calloc(argc+1, sizeof(char*));
	free(new_argv1);
	/* freed once again */
	return 0;
}





Quantitative Aptitude
Reasoning
Programming
Interview