malloc时写入大小为4的无效

时间:2012-09-16 19:31:08

标签: c malloc valgrind

我的程序是这样的:

char *line = "hello a b c d e f g ";
/* split it into words */
char **argv = NULL;
**argv = malloc(sizeof(char*));
if (*argv = NULL)
    printf("null malloc");
    printf("malloc ok");
    int i;
    for (i=0;;i++){
        printf("i=%d", i);
        line = strwrd(line, argv[i], 1024, " \t");
        printf("strwrk ok");
        if (argv[i] = NULL)
             break;
        **argv = realloc(*argv, (i+2)*sizeof(char*));   
        printf("realloc ok");
    }
}

当我在valgrind中运行时,它说:

==22169== Invalid read of size 4
==22169==    at 0x804858B: main (printTest.c:27)
==22169==  Address 0x0 is not stack'd, malloc'd or (recently) free'd

因为我是C的新秀,所以我不知道malloc是否有错误。

1 个答案:

答案 0 :(得分:1)

**argv = malloc(sizeof(char*));

应该是

argv = malloc(sizeof(*argv));