繁体   English   中英

访问结构会导致分段错误

[英]Accessing a struct causes segmentation fault

为什么要访问struct vm时出现分段错误? 代码如下:

BOOLEAN vm_init(struct vm * vm)
{
    struct vm_node * vmNode;
    vmNode = malloc(sizeof(struct vm_node));
    vm->item_list->head = vmNode;
    vm->coinsfile = " ";
    vm->foodfile = " ";
    return FALSE;
}

/* 
 * Loads data from the .dat files into memory. 
 * */
BOOLEAN load_data(struct vm * vm, const char * item_fname, 
                  const char * coins_fname) {
    FILE *file;
    file = fopen(item_fname, "r+");
    char buf[256]={};
    struct vm_node *vmNode;
    vmNode = malloc(sizeof(struct vm_node));
    vmNode->next = NULL;

    while (fgets(buf, sizeof buf, file) != NULL) {
        addNodeBottom(buf,vmNode);
    }

    /* Test reason for reaching NULL. */
    if (feof(file)) /* if failure caused by end-of-file condition */
    {
    }
    else if (ferror(file)) /* if failure caused by some other error      */
    {
        perror("fgets()");
        fprintf(stderr, "fgets() failed in file %s at line # %d\n", __FILE__,
                __LINE__ - 9);
        exit(EXIT_FAILURE);
    }
    fclose(file);

如果我尝试访问vm->item_list->head则会出现segfaults。 item_list是链接列表的容器,它是vmNode 所以我需要将vmNode存储在vm->item_list->head

但是,如果我执行以下操作:

vm->item_list->head = vmNode; //it segfaults... 

有什么线索吗?

vm和vm_node的typedef如下。

struct stock_item
{
    char id[IDLEN+1];
    char name[NAMELEN+1];
    char description[DESCLEN+1];
    struct price price;
    unsigned on_hand;
};

/* The data structure that holds a pointer to the stock_item data and a
 * pointer to the next node in the list
 */
struct vm_node
{
    struct stock_item * data;
    struct vm_node * next;
};

/* The head of the list - has a pointer to the rest of the list and a 
 * stores the length of the list 
 */
struct vm_list
{
    struct vm_node * head;
    unsigned length;
};

/* This is the head of our overall data structure. We have a pointer to 
 * the vending machine list as well as an array of coins. 
 */
struct vm
{
    struct vm_list * item_list;
    struct coin coins[NUMDENOMS];
    char * foodfile;
    char * coinsfile;
};
/* This is the head of our overall data structure. We have a pointer to 
 * the vending machine list as well as an array of coins. 
 */
struct vm
{
    struct vm_list item_list;
    struct coin coins[NUMDENOMS];
    char * foodfile;
    char * coinsfile;
};

一个小修复。 item_list只是一个指针和一个int。 这会在struct vm为其分配内存
您有指针,但没有指针应指向的结构。

您现在必须使用

vm.item_list->head = vmNode;

设置初始节点时。

那应该可以解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM