Visual Studio 2008 - 在C中编译
我正在编写一个链表应用程序但是当我尝试释放每个节点时,我会抛出一个异常。我唯一能想到的是我在add函数中分配了我的内存,也许我不能在另一个函数中释放它。公寓,我什么都想不到。
非常感谢任何建议,
#include <stdio.h>
#include <stdlib.h>
static struct convert_temp
{
size_t cel;
size_t fah;
struct convert_temp *next;
} *head = NULL, *tail = NULL;
=======
/** Add the new converted temperatures on the list */
void add(size_t cel, size_t fah)
{
struct convert_temp *node_temp = NULL; /* contain temp data */
node_temp = malloc(sizeof(node_temp));
if(node_temp == NULL)
{
fprintf(stderr, "Cannot allocate memory [ %s ] : [ %d ]\n",
__FUNCTION__, __LINE__);
exit(0);
}
/* Assign data */
node_temp->cel = cel;
node_temp->fah = fah;
node_temp->next = NULL;
if(head == NULL)
{
/* The list is at the beginning */
head = node_temp; /* Head is the first node = same node */
tail = node_temp; /* Tail is also the last node = same node */
}
else
{
/* Append to the tail */
tail->next = node_temp;
/* Point the tail at the end */
tail = node_temp;
}
}
=====
/** Free all the memory that was used to allocate the list */
void destroy()
{
/* Create temp node */
struct convert_temp *current_node = head;
/* loop until null is reached */
while(current_node)
{
struct convert_temp *next = current_node->next;
/* free memory */
free(current_node);
current_node = next;
}
/* Set to null pointers */
head = NULL;
tail = NULL;
}
答案 0 :(得分:12)
node_temp = malloc(sizeof(node_temp));
分配结构指针的大小而不是结构,你应该使用sizeof(*node_temp)
。
答案 1 :(得分:5)
此行未分配正确的内存量:
node_temp = malloc(sizeof(node_temp));
它应该是这样的:
node_temp = malloc(sizeof *node_temp);
答案 2 :(得分:3)
变化:
node_temp = malloc(sizeof(node_temp));
为:
node_temp = malloc(sizeof(struct convert_temp));
它会起作用。 sizeof(node_temp)
是指针的大小(最可能是4或8个字节);你想分配结构的大小