【发布时间】:2014-10-16 05:54:05
【问题描述】:
当我访问结构 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;
};
【问题讨论】:
-
显示的代码中没有任何地方
item_list分配给除 null 之外的任何内容。这是如何初始化的? -
@dbc 我改变了它,现在它被初始化为一个空的 vm_node 结构。
-
@JoshuaTheeuf 使用调试器找出您收到分段错误的位置。
-
你在哪里为 struct vm 分配内存?在不分配内存的情况下,您试图向 struct vm 中的元素写入一些值
-
在显示的代码中没有任何地方分配
struct vm_list并将其分配给item_list。由于malloc不会用零填充内存,所以vm->item_list是一个未初始化的指针。调试它,看看有什么问题。
标签: c struct linked-list segmentation-fault