I am reading the book "Effective C" by Robert C. Seacord. In this book, it has an exercise where you intentionally double-free a pointer so you can test using dmalloc to debug the cause. However, it doesn't fail as expected.
#include <string.h>
#include <stdlib.h>
#ifdef DMALLOC
#include "dmalloc.h"
#endif
void usage(char *msg) {
fprintf(stderr, "%s", msg);
free(msg);
return;
}
int main(int argc, char *argv[]) {
if (argc != 3 && argc !=4) {
/* The error message won't be more than 80 chars */
char *errmsg = (char *)malloc(80);
sprintf(
errmsg,
"Sorry %s,\nUsage: caesar secret_file keys_file [output_file]\n",
getenv("USER")
);
usage(errmsg);
free(errmsg);
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
Its clear here that *errmsg
should get freed twice:
First by the usage
function when its passed to it, and then right after in main
.
Why doesn't this fail when ran with no arguments? I am using linux (POP!_OS 20.04) with GCC 9.3.0.
EDIT: For more context the book suggests I should see an output like this:
% ./caesar
Sorry student,
Usage: caesar secret_file keys_file [output_file]
debug-malloc library: dumping program, fatal error
Error: tried to free previously freed pointer (err 61)
Aborted (core dumped)
Adding more calls to free doesn't do anything either. I get the usage portion but not a core dump.
I am sorry for taking up people's time with this. I figured it out.
That crash behavior is supposed to be provided by dmalloc, however its usage has changed a little since the writing of the book I am reading.
I needed to add -DDMALLOC_FUNC_CHECK
to the compiler options in order for it to produce the expected result.
I learned its dmalloc, not the OS that causes the program to crash when you double-free the pointer.