我正在读Robert C. Seacord写的"Effective C“这本书。在这本书中,它有一个练习,你可以故意双释放一个指针,这样你就可以使用dmalloc来调试原因。然而,它并没有像预期的那样失败。
#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);
}这里很清楚,*errmsg应该被释放两次:第一次是在usage函数传递给它的时候,然后是在main中。为什么在没有参数的情况下运行时不会失败?我使用的是带有GCC 9.3.0的linux (POP!_OS 20.04)。
编辑:对于更多的上下文,书中建议我应该看到这样的输出:
% ./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)向free添加更多的调用也不会有任何效果。我得到了使用部分,但不是核心转储。
发布于 2021-02-10 20:33:55
我很抱歉在这件事上占用了人们的时间。我想通了。这种崩溃行为应该是由dmalloc提供的,但是自从我正在阅读的这本书的写作以来,它的用法发生了一些变化。我需要将-DDMALLOC_FUNC_CHECK添加到编译器选项中,以便它能产生预期的结果。
我学习了它的dmalloc,而不是当你双击指针时导致程序崩溃的操作系统。
https://stackoverflow.com/questions/66136760
复制相似问题