当我访问结构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
它的段错误。 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;
};
答案 0 :(得分:0)
/* 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;
设置初始节点时。
这应该可以解决你的问题。