NO

Author Topic: Function scope vars and goto  (Read 3261 times)

JohnF

  • Guest
Function scope vars and goto
« on: December 20, 2005, 02:58:32 pm »
I've just noticed a possible problem when using goto and vars declared below where the goto is. Maybe you already knew about it.

Code: [Select]

int main(void)
{
int dummy = 0;

if(dummy == 0)
goto ende;

char * pStr = malloc(200);

ende:
if(pStr)
free(pStr);

return 0;
}


In the above simple code snippet pStr has function scope and is freed even though it has never been allocated.

I found a simpler problem in my FindFile app in IDragDrop.c. Unless an error occurs one may not notice this problem when in development. At least I didn't.

Have updated FindFile (HandleDragDrop) with these changes.

John

kobold

  • Guest
Function scope vars and goto
« Reply #1 on: December 20, 2005, 06:21:54 pm »
Why do you use goto? :-k
And why do you declare the var in the middle of your program?
(Perhaps thats why i never discovered such a problem.)

JohnF

  • Guest
Function scope vars and goto
« Reply #2 on: December 20, 2005, 11:15:48 pm »
Quote from: "kobold"
Why do you use goto? :-k
And why do you declare the var in the middle of your program?
(Perhaps thats why i never discovered such a problem.)


Sometimes it is convenient to use goto, as is declaring variables closer to where they are being used. Being able to declare variables that way was introduced in the C99 standard as it is popular I guess.

Without a goto one either has to duplicate cleanup code or have more IF's causing sometimes deeply indented code.

Of course that little snippet posted above is a simple case but when a function is two hundred lines and one needs to cleanup at various places it is easy to make that mistake.

John