运行 malloc 后内存损坏

Memory corruption after running malloc

我正在写一个宠物项目(一种单线程的 C 类 Lisp 语言解释器),我遇到了以下问题:指针被覆盖,而 malloc() 是 运行.显示所有代码会太长,但如有必要,我可以分享。我想了解如何调试问题。

错误发生在 运行 是用户定义函数的子例程中:

/* Determine the amount of arguments to the called function */
int argc = ast_len(fn_args)
printf("%s:%d %p\n", __FILE__, __LINE__, (void*) scope->vars->tail);
/* Allocate the memory to store the array of pointers to each of the arguments */
struct YL_Var** argv = malloc(sizeof(struct YL_Var*)*argc);
printf("%s:%d %p\n", __FILE__, __LINE__, (void*) scope->vars->tail);

您将得到以下输出:

interpreter.c:549 0x5558371c9480
interpreter.c:551 0x411
Segmentation fault (core dumped)

指针 scope->vars->tail 在调用 malloc() 期间被覆盖!

使用gdb和硬件断点可以清楚的看到malloc.c里面的值被覆盖了。

由于指针被覆盖,程序很快就会在 gdb 和正常 运行 中出现段错误。然而,当在 valgrind 中 运行 时,它不会出现段错误,它甚至会成功结束。 所以这是我的问题。你将如何开始调试这个烂摊子?我是在寻求建议,而不是在寻求答案。 我远不是 C 专家 :)

我想我有错,这当然不是 glibc-2.26 或 gcc 7.2.0 中的错误。

感谢大家的评论,我找到问题了

scope->vars 分配不当(如某些人所说)。 使用valgrind时,我发现了以下信息:

==23054== Invalid write of size 8
==23054==    at 0x10A380: varlist_prepend (interpreter.c:277)
==23054==    by 0x109548: main (yl.c:39)
==23054==  Address 0x5572a98 is 0 bytes after a block of size 8 alloc'd
==23054==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==23054==    by 0x10A304: varlist_prepend (interpreter.c:274)
==23054==    by 0x109548: main (yl.c:39)
==23054==

我的代码是这样的:

struct YL_VarList* vars = malloc(sizeof(vars));

如您所见,* 丢失了。 这是更正后的版本:

struct YL_VarList* vars = malloc(sizeof(*vars));

sizeof(vars) 会 return struct YL_VarList* 的大小,而我想分配 struct YL_VarList.

的大小