gpt4 book ai didi

c - 读取结构中的数组会导致段错误

转载 作者:行者123 更新时间:2023-11-30 19:03:15 25 4
gpt4 key购买 nike

我创建了一个链表,每个节点都包含一个结构作为元素和一个指向下一个节点的指针,如下所示

list.h

typedef struct node {
group data;
struct node *next;
} node;

typedef struct group {
unsigned int elements_count;
unsigned int closed;
unsigned int members[4];
} group;

list.c

node *add(node *head, group toadd) {
node *n_node = (node*) malloc(sizeof(node));
if(n_node != NULL) {
n_node->next = head;
group *n_group = &n_node->data;
/* Copy the values of the group into the created node */
n_group->elements_count = toadd.elements_count;
n_group->closed = toadd.closed;
for(int i = 0; i < 4; i++)
n_group->members[i] = toadd.members[i];
}
else {
throw_error("malloc returned a NULL pointer");
}
return n_node;
}

当我尝试读取数组的第一个元素(node->data.members[0])时出现问题。Valgrind 表示问题是大小为 4 的无效读取,其中地址未进行堆栈、分配或(最近)释放。即使我使用了 malloc 来分配每个节点,为什么也会出现段错误?

EDIT:

ma​​in.c

node *group_list = NULL;

/* Other code here.. */

group *cur_group = is_present(group_list, msg_gest.mtype);

if(cur_group == NULL) {
// The group isn't still present in the group list, then add it
group new_group = {
.elements_count = 0,
.closed = 0,
.members = {-1, -1 , -1, -1}
};

new_group.members[new_group.elements_count++] = msg_gest.mtype;
new_group.members[new_group.elements_count++] = msg_gest.to_add;
new_group.closed = msg_gest.to_close;
group_list = add(group_list, new_group);
} else {
cur_group->members[cur_group->elements_count++] = msg_gest.to_add;
cur_group->closed = msg_gest.to_close;
}

存在

group* is_present(node *head, int matr) {

group *c_group;
node *c_node = head;

while(c_node != NULL) {

c_group = &c_node->data;


if(*(c_group->members) == matr) // !!Segmentation fault is caused by this read
return c_group;
printf("\n%d", *(c_group->members));

c_node = c_node->next;
}
return NULL;
}

最佳答案

我认为问题是由堆溢出引起的,为了解决这个问题,我修改了节点结构,如下

typedef struct node {
group* data;
struct node *next;
} node;

我在 add 函数中分配了组,如下所示

n_node->data = (group*) malloc(sizeof(group));

关于c - 读取结构中的数组会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54293304/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com