Hacker News new | past | comments | ask | show | jobs | submit login

Loops in C introduce a new lexical scope, so the defer runs once for every loop iteration.

Assuming you are using defer for destructor purposes, and use it where you declare your variable, this would generally be what you want, as it frees the memory at the same time it goes out of scope.

The flip side of this is that code like the following would be broken:

    char *foo = NULL;
    if (true) {
         foo = calloc(1,1);
         defer { free(foo); }
    }
    char c = *foo;
As foo gets freed at the end of the conditional, which is prior to the dereference.



That particular example is easy - just put the defer before the if.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: