2009-12-20 77 views
1

的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; 
} 
+1

請注意,這是一個很好學習的習慣用法:'T * a = malloc(size * sizeof * a);'這種類型在'a'中存在變化,分配適量的空間,並且很容易閱讀。 – 2009-12-20 16:35:33

回答

12

node_temp = malloc(sizeof(node_temp));被分配的大小結構指針而不是結構,你應該使用sizeof(*node_temp)

+0

+1因爲您可以輸入比我更快的速度:-) – paxdiablo 2009-12-20 12:30:54

5

此行不分配正確的內存量:

node_temp = malloc(sizeof(node_temp)); 

應該不是這樣:

node_temp = malloc(sizeof *node_temp); 
3

變化:

node_temp = malloc(sizeof(node_temp));

到:

node_temp = malloc(sizeof(struct convert_temp));

它會工作。 sizeof(node_temp)是指針的大小(最可能是4或8字節);你需要分配結構的大小