2009-12-20 4 views
1

비주얼 스튜디오 2008 - 나는 연결리스트의 응용 프로그램을 쓰고 있어요하지만 각 노드를 시도하고 무료 할 때 내가 던진 예외가 C는 메모리를하려고 할 때 오류가 발생

에서 컴파일. 내가 생각할 수있는 유일한 점은 add 함수에서 메모리를 할당했다는 것입니다. 아마도 globaly로 다른 메모리에서 메모리를 해제 할 수 없습니다. Appart에서 나는 아무것도 생각할 수 없다. 어떤 조언을

많은 감사,

#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'에서 타입 변경을 견디고 올바른 양을 할당합니다 공간을 차지하며 읽기 쉽습니다. –

답변

12

node_temp = malloc(sizeof(node_temp));이의 크기를 할당한다 구조체 포인터 대신 struct 포인터를 사용하려면 sizeof(*node_temp)을 사용해야합니다.

node_temp = malloc(sizeof(node_temp)); 

대신이 있어야한다 :

node_temp = malloc(sizeof *node_temp); 
+0

+1보다 빨리 입력 할 수 있기 때문에 :-) – paxdiablo

5

이 라인은 적절한 양의 메모리를 할당하지 않습니다

node_temp = malloc(sizeof(struct convert_temp));

및 작동합니다. sizeof(node_temp)은 포인터 크기입니다 (대체로 4 또는 8 바이트 임). 당신은 구조체의 크기를 할당하려고합니다.

3

변경 :

node_temp = malloc(sizeof(node_temp));

에 :

관련 문제