Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will using goto cause memory leaks?

I have a program in which i need to break out of a large bunch of nested for loops. So far, the way most people have been telling me to do it is to use an ugly goto in my code.

Now, if i create a bunch of local stack (i think that's what they are called, if not, i mean just regular variables without using the new command) variables inside my loops and my program hits that one if statement that triggers the goto, will i encounter a memory leak due to my program exiting many loops improperly and not cleaning up the local variables?

like image 794
Faken Avatar asked Aug 11 '09 02:08

Faken


2 Answers

Stack variables (autos, not autobots) aren't "leaky" like variables allocated via new() or malloc().

As far as the "uglyness" of gotos that's just dogmatic. Read Knuth, he was just as brilliant as Dijkstra. http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf Avoid pasta based programming, but careful use won't degrade into spaghetti.

Dijkstra didn't like them BECAUSE most of what you can do with gotos can be done with other structured programming techniques and uses less code therefore making the other structured less error prone.

Understand that gotos shouldn't be your first solution, and don't go out of your way to use them, but if it makes sense don't submit to dogmatic lench mobs. The break statement is a just a goto in disguise designed for cases where strict adhearance to the "Thou shalt not use gotos" commandment didn't make sense.

like image 159
NoMoreZealots Avatar answered Oct 03 '22 00:10

NoMoreZealots


No, you will not cause a memory leak. Using a goto is not "exiting loops improperly." It's just not generally recommended from a code-structure point-of-view.

That aside, when you leave the loop, the local variables will go out of scope and be popped off of the stack (i.e. cleaned up) in the process.

like image 26
Robert Cartaino Avatar answered Oct 03 '22 00:10

Robert Cartaino