c-访问结构会导致分段错误



为什么访问结构体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 # %dn", __FILE__,
                __LINE__ - 9);
        exit(EXIT_FAILURE);
    }
    fclose(file);

如果我尝试访问vm->item_list->head,它会出错。item_list是链表的容器,这就是vmNode。所以我需要将vmNode存储在vm->item_list->head中。

但如果我做以下操作:

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

有线索吗?

vm和vm_node的类型定义如下。

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;

当设置初始节点时。

这应该能解决你的问题。

相关内容

  • 没有找到相关文章