我有一个动态分配的结构数组。我正在编写一个函数,向该数组添加新的结构条目。每次调用该函数时,都应该重新分配数组的空间。
pa->arr = realloc(pa->arr, (pa->count + 1) * sizeof(struct product));
if (pa->arr == NULL)
return NULL;
结构数组arr由另一个结构struct Product_array *pa维护,除了指向数组*arr的指针之外,该结构还包含< strong>count(数组条目数)。
struct product_array {
struct product *arr;
unsigned int count;
};
struct product {
char *title;
};
此外,我必须为标题字段单独分配空间。
char *temp = malloc(strlen(title) + 1);
if (temp == NULL){
return NULL;
}
strcpy(temp, title);
title = temp;
pa->arr[pa->count].title = title;
该函数有效,但我收到 Valgrid 提示“无效读取大小 8”。如果您能帮助我,我将非常感激。
最佳答案
您收到的错误表明您正在从未分配的内存中读取数据。
也许你错过了这个:
pa->arr[pa->count - 1].title = title;
不是 pa->arr[pa->count].title = title;
** 我想将此作为评论发布,但仍然没有足够的声誉!
关于c - 为结构数组分配空间,Valgrind 无效读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29511520/