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.