1

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?

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.

bongadonga
  • 13
  • 3

2 Answers2

0

assert(s == NULL); // Causes assert failure.

Code has not changed main()'s s as calling free_struct(s); does not affect the value of s here.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

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.)

ikegami
  • 367,544
  • 15
  • 269
  • 518