1

Where is this behaviour documented (if it is at all)?

When you declare a pointer in C in the middle of a block, it will probably be in a wrong state (pointing to unusable memory) and you cannot use the standard if (a) free(a) for freeing it.

The simplest program that comes to mind is

#include <stdlib.h>
int main(int argc, char *argv[]){
    if(argc > 1) goto END;
    char *a = NULL;
    a = calloc(1,1);
END:
    if(a) free(a);
}

Run the program without parameters and it works OK, if you run it with at least one parameter, it will probably break as follows: suprisingly (to me), if you compile it with clang, it may work (on my OS X it does, but on a NetBSD it does not). If you do with gcc, it always returns a

malloc: *** error for object 0x7fff5fc01052: pointer being freed was not allocated

Notice that the same program with the declaration at the head of the block is correct.

Edit: Notice that the question is about documentation. I realize doing what I describe is unsafe but I have found no place where it is explicitly shown.

pfortuny
  • 13
  • 3

1 Answers1

3

The "pattern"

if(a) free(a);

is certainly not standard, or at least it shouldn't be. It's safe to pass NULL to free(), so the if adds nothing.

I would expect the value of a to be undefined (not likely to be NULL) if you jump past the initialization, which makes perfect sense to me. This is really hairy code, don't do this.

It could be argued that the existance of the goto and label imply a scope that isn't implemented, and there's no reason at all that the free(a); statement is after the label (outside the "invisible" scope where a is defined).

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Thanks about the if(NULL), you are right. The 'Don't do this' is what bothers me... I would gladly goto the end of a function to free() any allocated pointers. What I did not know (I can see it nowhere, which is my question) is that those pointers are in a wrong state, not NULL. So the place of the declaration is quite relevant for pointers. – pfortuny Apr 18 '13 at 10:09
  • There's nothing "wrong" about it, you're simply doing something ill-advised. See also [this question](http://stackoverflow.com/questions/2821663/c99-goto-past-initialization) about pretty much the same thing. – unwind Apr 18 '13 at 10:16
  • Great. Sorry you had to do my own homework but I could not come up with the precise wording. Done. – pfortuny Apr 18 '13 at 10:19