Will using goto cause memory leaks?

2019-02-21 12:44发布

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?

10条回答
劳资没心,怎么记你
2楼-- · 2019-02-21 13:32

Nope. Local variables do not need to be individually cleaned up. When the stack pops, all the local variables will go away right along with it.

查看更多
Rolldiameter
3楼-- · 2019-02-21 13:32

No you will not.

However, make sure that any external resources are properly released. For example, if you opened a file it would be possible to jump past where it would normally be closed.

查看更多
霸刀☆藐视天下
4楼-- · 2019-02-21 13:36

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.

查看更多
在下西门庆
5楼-- · 2019-02-21 13:37

No. You can only leak memory that is dynamically allocated.

查看更多
登录 后发表回答