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);
}
这里是完整的代码,
Callee
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;
}
Caller不同的文件/作用域
char **data = getList();
for (char **ptr = data; *ptr; ptr++) { // warning -> Conditional jump or move depends on uninitialized values(s)
free(*ptr);
}
free(data);
基于新板的建议撰写,我没有收到strlen + memcpy
评论,请提出建议。
char **getList(void) {
const char * const list[] = {"John", "Jane", NULL};
unsigned int size = 0;
char **ptr;
for (ptr = (char **) list; *ptr != NULL; ptr++) {
size++;
}
char **data = malloc(sizeof(char *) * (size + 1));
if (data == NULL) goto exception;
ptr = (char **) list;
for (unsigned int i = 0; *ptr != NULL; ptr++, i++) {
data[i] = malloc(sizeof(char) * (strlen(*ptr) + 1));
if (data[i] == NULL) goto exception;
strcpy(data[i], *ptr);
}
data[size] = NULL;
return data;
exception:
fprintf(stderr, "data Allocation failed.\n");
return NULL;
}