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

It's a very common pattern for C memory allocation checking. A public example I know off the top of my head can be seen here: https://github.com/zedshaw/learn-c-the-hard-way-lectures/blo... (the implementation of the CHECK macro). That's in a C tutorial but I've implemented a version of that macro frequently.

Let's say you need to dynamically allocate two buffers in a function and want to make sure they are freed at the end of your call. You can use this macro like so:

  int two_bufs(int n, int m) {
    int *buf_1 = NULL;
    int *buf_2 = NULL;
    buf_1 = calloc(n, sizeof(int));
    CHECK(buf_1);
    buf_2 = calloc(m, sizeof(int));
    CHECK(buf_2);
 
    // ... lots of cool things with buf_1 and buf_2

  error:
    free(buf_1);
    free(buf_2); // Safe if null

  }



You have "free(buf_2); // Safe if null", but if CHECK(buf_1) turns into a "goto error", won't buf_2 be uninitialized? And so can take on any value?


You are correct, will edit. C is hard, writing C in the browser sans coffee is harder. :-)


I do think this illustrates one of the issues with goto: normally the compiler would be able to warn that you were using buf2 potentially uninitialized, but I think you wouldn't get a warning in this case.


One of the examples in the linked article showed the compiler emitting a warning when a variable wasn't initialized because the goto skipped past that line, it's in 31.7. I don't know what compilers will or will not give you that warning, but at least the one used for the article does. So it ought to catch the problem with the initial version of the example above as well.


The Clang Static Analyzer could probably find this, if the compiler itself doesn't notice.




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

Search: