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

时间:2019-01-21 15:42:41

标签: c unix memory struct

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

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分配每个节点,为什么也会出现分段错误?

  

编辑:

main.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;
}

2 个答案:

答案 0 :(得分:1)

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

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

我像这样在add函数中分配了组

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

答案 1 :(得分:0)

尝试替换行

if(*(c_group->members) == matr)

使用

if(c_group->members[0] == matr)