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;
Run Code Online (Sandbox Code Playgroud)
=======
/** 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;
}
}
Run Code Online (Sandbox Code Playgroud)
=====
/** 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;
}
Run Code Online (Sandbox Code Playgroud)
此行不分配正确的内存量:
node_temp = malloc(sizeof(node_temp));
Run Code Online (Sandbox Code Playgroud)
它应该是这样的:
node_temp = malloc(sizeof *node_temp);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
613 次 |
| 最近记录: |