4

重複
の可能性: 割り当てられた文字列を出力するときに 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(); の前にエラーが発生しない理由がわかりませんでした。

4

0 に答える 0