我一直在 Valgrind 中看到这些错误。我的程序也有段错误,但我试图先解决 Valgrind 中的错误。
81 char *ptr = NULL;
82 if (addition_is_safe(sz, TRAILER_SZ))
83 ptr = malloc(sz + TRAILER_SZ);
84 syslog(LOG_NOTICE, "Calling set trailer value, ptr=%p", ptr);
将其打印到日志中:
9 月 17 日 00:05:50 设备 m61[18301]:调用设置预告值,ptr=0x96af158
瓦尔格林:
==18069== 2 errors in context 1 of 4:
==18069== Invalid read of size 1
==18069== at 0x402BCCA: memcpy (mc_replace_strmem.c:882)
==18069== by 0x8048819: main (test025.c:13)
==18069== Address 0x4213709 is 137 bytes inside a block of size 368 free'd
==18069== at 0x4028F0F: free (vg_replace_malloc.c:446)
==18069== by 0x40AA00B: fclose@@GLIBC_2.1 (iofclose.c:88)
==18069== by 0x4136003: __vsyslog_chk (syslog.c:228)
==18069== by 0x4136446: syslog (syslog.c:119)
==18069== by 0x8049823: attempt_create_allocation (m61_allocation_core.c:84)
==18069== by 0x8048914: m61_malloc (m61.c:47)
==18069== by 0x80487B4: main (test025.c:9)
==18069==
编辑:我运行的测试代码实际上是为了产生一个无效的自由,以便在 Valgrind 和我的内存调试代码中捕获。但是,它不应该发生段错误,这就是正在发生的事情。一旦我关闭 syslog,就不再有 seg 故障,并且 Valgrind 报告与测试代码的预期一致。我不知道为什么 syslog 会导致上述问题。
测试代码:
1 #include "m61.h"
2 #include <stdio.h>
3 #include <assert.h>
4 #include <string.h>
7 int main() {
8 char *a = (char *) malloc(200);
9 char *b = (char *) malloc(50);
10 char *c = (char *) malloc(200);
11 char *p = (char *) malloc(3000);
12 (void) a, (void) c;
13 memcpy(p, b - 200, 450);
14 free(p + 200);
关闭 Valgrind 后的新 Valgrind 报告:
==5688== 18 errors in context 1 of 3:
==5688== Invalid read of size 4
==5688== at 0x402BD00: memcpy (mc_replace_strmem.c:882)
==5688== by 0x8048849: main (test025.c:13)
==5688== Address 0x41f92c0 is 16 bytes before a block of size 208 alloc'd
==5688== at 0x4029F6F: malloc (vg_replace_malloc.c:270)
==5688== by 0x80497AD: attempt_create_allocation (m61_allocation_core.c:77)
==5688== by 0x8048950: m61_malloc (m61.c:48)
==5688== by 0x8048804: main (test025.c:10)