Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Weird assert failure after a struct free in C

I am a beginner in C and I encountered this weird assert failure:

assuming we have this setup:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>

typedef struct {
    int id;
} Struct;

Struct* new_struct(int id) {
    Struct* s;
    if ((s = malloc(sizeof(Struct))) == NULL) {
        return NULL;
    }
    s->id = id;
    return s;
}

void free_struct(Struct* s) {
    if (!s) {
        return;
    }
    free(s);
    s = NULL;
    assert(s == NULL); // no problem here, `s` is NULL.
}

int main(void) {
    Struct* s = new_struct(4);
    printf("%d\n", s->id);
    
    free_struct(s);
    assert(s == NULL); // Causes assert failure.
    
    return EXIT_SUCCESS;
}

why does the assert(s == NULL) inside the main function fail but the one at the last line of the free_struct() function pass?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried to debug what is happening but with no results.

EDIT:
I added return s; to the new_struct() function but that wasn’t the thing that caused this weird assert failure it still happens.

>Solution :

First of all, you forgot to return s; in new_struct, so the behaviour of your program is undefined. (Always enable your compiler’s warnings!)

But even after you fix this, you will see the same behaviour. And that’s beacuse free_struct(s) does not modify main‘s s. Arguments are passed by value, which means that free_struct‘s s is completely independent of main‘s s. You change free_struct‘s s, but not main‘s s.

You could use the following:

#define free_struct(s) { free(s); s = NULL; }

(No need to check if s is NULL.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading