可能重复:
打印分配的字符串时 valgrind 报告错误
我有简单地复制字符串的代码。我记得分配内存,但 valgrind 显示一些错误,我不明白这一点。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct foo {
char *a;
};
struct foo*
create(char *lol){
struct foo *test = malloc(sizeof(struct foo));
test->a = malloc(sizeof(char) * (strlen(lol)+1));
strcpy(test->a, lol);
return test;
}
int main()
{
char *a = malloc(5*sizeof(char));
strcpy(a, "test");
struct foo *c = create("test");
printf("%s\n%s\n", a, c->a);
printf("%s\n", c->a);
free(a);
free(c->a);
free(c);
return 0;
}
给出 valgrind 输出:
==13825== Memcheck, a memory error detector
==13825== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==13825== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==13825== Command: ./a.out
==13825==
test
test
==13825== Invalid read of size 4
==13825== at 0x40C301B: ??? (in /lib/libc-2.14.1.so)
==13825== by 0x4066242: (below main) (in /lib/libc-2.14.1.so)
==13825== Address 0x41ca09c is 4 bytes inside a block of size 5 alloc'd
==13825== at 0x402A018: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==13825== by 0x80484F3: create (in /home/patseb/src/mgr/test/a.out)
==13825== by 0x8048550: main (in /home/patseb/src/mgr/test/a.out)
==13825==
test
==13825==
==13825== HEAP SUMMARY:
==13825== in use at exit: 0 bytes in 0 blocks
==13825== total heap usage: 3 allocs, 3 frees, 14 bytes allocated
==13825==
==13825== All heap blocks were freed -- no leaks are possible
==13825==
==13825== For counts of detected and suppressed errors, rerun with: -v
==13825== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 13 from 8)
我不明白为什么在第一次 printf() 之前没有发生错误;