简体   繁体   中英

cannot free memory (assertion error)

I'm getting an assertion error (expression: crtisvalidheappointer) when I try to free my circular buffer. Why is this happening?

Relevant structs:

typedef struct quote {
    unsigned int seconds;
    double rate;
} quote;

typedef struct cbuf {
    unsigned int max;
    unsigned int start;
    unsigned int end;
    unsigned int size;
    quote *quotes;
} cbuf;

Block of code that mallocs and frees:

#define INITIAL_SIZE 10
static cbuf cb1 = {INITIAL_SIZE, 0, 0, 0, NULL};
cb1.quotes = (quote*)malloc(INITIAL_SIZE * sizeof(quote));
if(cb1.quotes == NULL)
{
    printf("Error - memory allocation failed.");
    exit(1);
}

free(&cb1);
free(&cb1);

You're trying to free the memory where cb1 resides, but

static cbuf cb1 = {INITIAL_SIZE, 0, 0, 0, NULL};

that was not malloc ed.

free(cb1.quotes)

is what you need to free.

您无法释放尚未分配的内容:

free(&cb1);

the only thing you need to remember is : you can free the memory only which you have dynamically allocated

in your case, you have dynamically allocated memory for "cb1.quotes" not for cb1 so you must free cb1.quotes not the cb1.

with regards

Hims

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM