I writed this code. Every letter got by getchar coming into a sequence of instances of structs... Than I make it free. Three scenario of work:
I press only Enter so the sequence is empty. Everything's fine.
I write line by line, and everything's fine
But somehow if I writed a non-empty line (like in sc.2) and then I just press Enter (like in sc.1) I got this error and app's crash:
free(): double free detected in tcache 2
#include <stdio.h> #include <stdlib.h> struct foo { char c; struct foo* p; }; struct foo* set_foo() { char c; struct foo* f; struct foo* sf; if ((c = getchar()) != '\n' && c != EOF) { f = malloc(sizeof(struct foo)); f->c = c; sf = f; while ((c = getchar()) != '\n' && c != EOF) { f->p = malloc(sizeof(struct foo)); f->p->c = c; f = f->p; } } return sf; } void free_foo(struct foo* f) { struct foo* sf; while (f != NULL) { sf = f; f = f->p; if (sf != NULL) { free(sf); } } } int main(int argc, char* argv[]) { while (1) { struct foo* f; f = set_foo(); free_foo(f); } return 0; }
Why double free. I even check it by comparing with NULL and free() only when it's not NULL.