News for hackers. Stuff that matters.
Re:Dangerous Embedded C Coding Standard Rules (2011) by Someone on Monday December 30, 2013 @04:31PM (#6987105)
So my source code, after a while, ended up looking more or less like this:

    if ((f = open_file()) == NULL)
        return ERROR_CODE;
    if ((s = allocate_string()) == NULL)
        return ERROR_CODE;
    if (write_string_to_file(s, f) < 0)
        return ERROR_CODE;*
I hope for you that's more 'less' than 'more'. That code leaks resources whenever an error occurs. Can't allocate the string? Oops, kept the file open. Write failed? Oops, kept the file open, and leaked the result of allocate_string.

In C, this kind of error handling screams for the use of goto:

    int result = ERROR_CODE;
    FILE * f = NULL;
    char * s = NULL;
    if((f = open_file()) == NULL) goto ERR;
    if((s = allocate_string() == NULL) goto ERR;
    ...
    result = NOERROR;
  ERR:
    if( s != NULL) free_string( s);
    if( f != NULL) close_file( f);
    return result;
Given that you need that to write robust code, I don't think the macros make things much clearer.
Re:Dangerous Embedded C Coding Standard Rules (2011) by ZoFreX on Monday December 30, 2013 @06:32PM (#6987838)
An advantage of using goto to handle errors is that you don't need that condition checking in the teardown:

    int result = ERROR_CODE;
    FILE * f = NULL;
    char * s = NULL;
    if((f = open_file()) == NULL) goto end;
    if((s = allocate_string() == NULL) goto closefile;
    if((some_other_thing() == NULL) goto freestring;
    ...
    result = NOERROR;
  freestring:
    free_string( s);
  closefile:
    close_file( f);
    return result;
Re:Dangerous Embedded C Coding Standard Rules (2011) by kstenerud on Monday December 30, 2013 @10:28PM (#6988762)
That's fine until you have multiple lines that goto closefile or freestring, and you mix them up at some point, or you try to refactor the code and forget to update one of your gotos. The resulting bug will wait beneath the waters until one day you get a mysterious "out of file descriptors" or "out of memory" error at some random place in your program after it's been running for awhile.

And really, the extra condition check likely isn't going to affect the critical path, but it will make it a lot easier to reason about the code, especially when someone else has to modify it.

Re:Dangerous Embedded C Coding Standard Rules (2011) by ZoFreX on Thursday January 02, 2014 @06:49AM (#6999183)
It's really a matter of both taste and situation. I've seen some very compelling examples from the Linux kernel where this is definitively easier to follow than the alternatives (Linus has made some good defences of goto for this purpose), but I've never felt it was the clearest option in any code I've written myself.