开发者

free throws error when trying to free memory

开发者 https://www.devze.com 2022-12-14 06:50 出处:网络
Visual Studio 2008 - compiling in C I am writing a linked list application but when I try and free each node I get an exception thrown. The only thing I can think of is that I allocated my memory in

Visual Studio 2008 - compiling in C

I am writing a linked list application but when I try and free each node I get an exception thrown. The only thing I can think of is that I allocated my memory in the add function, and maybe globaly I cannot free it in another function. Appart from that I can't think of anything.

Many thanks for any advice,

#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 = c开发者_开发问答el;
    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;
}


node_temp = malloc(sizeof(node_temp)); is allocating the size of a struct pointer instead of the struct, you should be using sizeof(*node_temp).


This line does not allocate the correct amount of memory:

node_temp = malloc(sizeof(node_temp));

It should instead be this:

node_temp = malloc(sizeof *node_temp);


Change:

node_temp = malloc(sizeof(node_temp));

to:

node_temp = malloc(sizeof(struct convert_temp));

and it will work. sizeof(node_temp) is the size of a pointer (most likely 4 or 8 bytes); you want to allocate the size of the structure

0

精彩评论

暂无评论...
验证码 换一张
取 消