的Visual Studio的2008 - 編譯使用C免費嘗試免費的內存時會拋出錯誤
我寫一個鏈表的應用程序,但是當我嘗試免費的每個節點我得到拋出的異常。我能想到的唯一的事情就是我在add函數中分配了我的內存,也許globaly我不能將它釋放到另一個函數中。公寓從那我什麼都想不到。
非常感謝任何建議,
#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;
}
請注意,這是一個很好學習的習慣用法:'T * a = malloc(size * sizeof * a);'這種類型在'a'中存在變化,分配適量的空間,並且很容易閱讀。 – 2009-12-20 16:35:33