简体   繁体   中英

calloc problem - malloc.c:2385 error - how does calloc/malloc work?

When running my program I receive following error:

malloc.c:2385: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.

The complete code is huge, but I have managed to find something interesting in reproduction, and I cannot understand why this is happening. Any help and/or explanation would be very much appreciated.

Here is a snippet of the code when it is not failing:

static void adjacent_list_get(struct elem **elem_list,
                          struct elem *element,
                          uint32_t *size) {

struct elem **t_elem_list;

t_elem_list = calloc((size_t) 1, sizeof(*t_elem_list));     

if (!elem_list) {       
...

And here is a snippet of the code when it fails:

static void adjacent_list_get(struct elem **elem_list,
                          struct elem *element,
                          uint32_t *size) {

struct elem **t_elem_list;

if (!elem_list) {   
        t_elem_list = calloc((size_t) 1, sizeof(*t_elem_list)); 
        ...

During execution, elem_list is NULL , so the if statement is true and it enters that block; but then it fails with error mentioned above.

I cannot understand how the same line, same calloc can fail in the same function depending on if it is inside or out of the if block. I am missing something here, and I could not find any explanation on the internet.

how does calloc/malloc work?

It depends a lot of your implementation.

Some implementations of calloc/malloc are open source: try installing Debian on your laptop, study the source code of GNU libc or musl-libc , and read Linux From Scratch . Then malloc would sometimes use system calls like mmap(2) or sbrk(2) . Most of the time malloc would reuse previously free d memory zones.

See also this answer for a joke-implementation of malloc which I believe is conforming to some C standard (eg n1570 or better).

On the other hand, reading the source code of malloc inside Windows is reserved to a very few happy fews.

On microcontrollers like Arduino , malloc works very differently.

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