News for hackers. Stuff that matters.
Re:Things Rust shipped without by luso_brazilian on Friday July 03, 2015 @05:50PM (#9828133)
I know it is just an example to illustrate the point but this seems to have a bug in it: resource2 won't be initialized if the function fail to allocate resource1 so resource2 will be null when the code enters the deallocation condition.

A way to fix it would be to return different failures for every allocation and to use a switch without a break to clean up, something like:

    switch (ret) {
      case EXIT_SUCCESS:
        free(resource2);
      case EXIT_FAILURE2: 
        free(resource1);
      case EXIT_FAILURE1:
        break;
    }
EDIT: added potential fix to the code. Sorry if there is any bug in the fix, my C is a little bit ... rusty.

EDIT2: fixed a bug in the fix. C is hard, let's go shopping.

EDIT3: the explanation for the bug was also wrong. It is not a memory leak for but freeing a null pointer. Fixed too.

Re:Things Rust shipped without by protopete on Friday July 03, 2015 @07:34PM (#9828479)
Passing a null pointer to free() is perfectly safe, and in this case simplifies the cleanup code.

Although the concern of a memory leak is valid. I would have expected the resources to be free'd regardless of the result.

Re:Things Rust shipped without by luso_brazilian on Friday July 03, 2015 @07:59PM (#9828550)
Of course, you are right. I seem to have carried the belief that freeing a null pointer was as bad as freeing one twice. And now I know.

Seems to be a common misconception [1], thanks for pointing out, that makes the GGP code correct in all counts and my switch redundant.

[1] https://news.ycombinator.com/item?id=8844031

Re:Things Rust shipped without by malka on Friday July 03, 2015 @09:28PM (#9828774)
Or you could simply free resource1 and resource2 even if the allocation failed. free(NULL) is defined to do nothing.
Re:Things Rust shipped without by TheLoneWolfling on Friday July 03, 2015 @09:23PM (#9828764)
Except of course that many languages seem to be trying to remove fallthroughs from switches too...