valgrind条件跳转或移动取决于未初始化

Valgrind对两行代码抛出两个警告,每行代码旁边的注释中都提到了该警告。

警告1:

大小为8的无效写入,地址...在一个大小的块内为8个字节   9已分配

data[size] = NULL;

警告2:

条件跳转或移动取决于未初始化的值
for (char **ptr = data; *ptr; ptr++) { // warning -> Conditional jump or move depends on uninitialized values(s)
    free(*ptr);
}

这是完整的代码,

被叫者

char **getList() {
    char **list = (char *[]) {"John", "Jane", NULL};

    int size = 0;
    for (char **ptr = list; *ptr; ptr++) {
        size++;
    }

    char **data = malloc(sizeof(char *) * size + 1);
    if (data == NULL) goto exception;

    for (int i = 0; *list; list++, i++) {
        data[i] = malloc(sizeof(char) * (strlen(*list) + 1));
        if (data[i] == NULL) goto exception;
        strcpy(data[i], *list);
    }

    data[size] = NULL; // this line gives warning
    // warning -> invalid write of size 8, Address ... is 8 bytes inside a block of size 9 alloc'd
    return data;

    exception:
    fprintf(stderr, "data allocation failed.\n");
    return NULL;
}

呼叫者

char **data = getList();

for (char **ptr = data; *ptr; ptr++) { // warning -> Conditional jump or move depends on uninitialized values(s)
    free(*ptr);
}
free(data);
评论