Live data from Hacker News

Show HN: A simple garbage collector for C

github.com

1–10 of 62 posts

Re: Show HN: A simple garbage collector for C

#5
post #4

I just wish C had something like defer in go, That would cover most cases.

Defer can be emulated with the block extensions of Clang and GCC [0], though I'm not sure how much I'd like to see something like that in a codebase.

[0] https://web.archive.org/web/20180426195701/http://fdiv.net/2...

Re: Show HN: A simple garbage collector for C

#7
post #5
post #4

I just wish C had something like defer in go, That would cover most cases.

Defer can be emulated with the block extensions of Clang and GCC [0], though I'm not sure how much I'd like to see something like that in a codebase. [0] https://web.archive.org/web/20180426195701/http://fdiv.net/2...

That link seems to be broken? Nothing opens when I click it.

Re: Show HN: A simple garbage collector for C

#8
post #7
post #5

Earlier quoted context omitted.

Defer can be emulated with the block extensions of Clang and GCC [0], though I'm not sure how much I'd like to see something like that in a codebase. [0] https://web.archive.org/web/20180426195701/http://fdiv.net/2...

That link seems to be broken? Nothing opens when I click it.

Works fine for me. It's using __attribute__((cleanup)) to call a function that calls the block you give it.

Re: Show HN: A simple garbage collector for C

#9
post #7
post #5

Earlier quoted context omitted.

Defer can be emulated with the block extensions of Clang and GCC [0], though I'm not sure how much I'd like to see something like that in a codebase. [0] https://web.archive.org/web/20180426195701/http://fdiv.net/2...

That link seems to be broken? Nothing opens when I click it.

It's a short article, and worth reading if you can work out why the Wayback Machine isn't working for you.

The magic is basically:

    static inline void defer_cleanup(void (^*b)(void)) { (*b)(); }
    #define defer_merge(a,b) a##b
    #define defer_varname(a) defer_merge(defer_scopevar_, a)
    #define defer __attribute__((cleanup(defer_cleanup))) void (^defer_varname(__COUNTER__))(void) =
Which let's you do:

    FILE *a = fopen ("a.txt", "r");
 
      if (!a)
        return EXIT_FAILURE;
      defer
      {
        fclose (a);
      };
It uses cleanup and blocks, both of which are extensions. There may also be some strangeness with the way blocks hold memory. (Block references become const copies).

Re: Show HN: A simple garbage collector for C

#10
post #4

I just wish C had something like defer in go, That would cover most cases.

If you're willing to use macros, this can do the trick. Return and break will preempt the expression, but continue should work fine.

  #define DEFER(EXPR) for(int _tmp=1; _tmp; _tmp=0,(EXPR))
Example:

  char * data = malloc(32);
  DEFER(free(data))
  {
          // do stuff
  }
Post reply on HN