In this video I will explain the importance of cleaning up resources when programming C. Dependencies: - lsof (can be obtained with your package manager for example in Ubuntu/Debian run "apt install lsof")
Another common pattern that I like to use with "goto cleanup" that I forgot to mention is saving the function return value in a local variable for example "bool succeeded = false;" and then changing it to true only right before the cleanup label, then you can just do "return succeeded" in the end of the function, and this way it can easily be checked if the function suceeded or failed.
I tend to prefer using an integer so that I can indicate where the failure occurs and either increment or decrement the return value after each success.
your use of man pages is incredible, if you're open to suggestions i would LOVE to watch a video of you detailing how to use man pages as effectively as you do. or how you figured out how to use them so well
Thank you for these videos. I'm a beginner and its really helpful for me to see how an experienced programmer not only program in C but also navigate file systems and use vim effectively.
Destructors are a great invention. It solves this Cleanup mess by making it the compilers problem. And the compiler is guaranteed to know every route to exit a scope.
This is great for Linux. Would you please create a short video of tracking resource/Handle leaks and memory leaks for Windows? All of the content I see online is trying to use plug-ins and things that don't work with the latest Visual Studio.
Nir, please, how is it possible to change the color of the title bar of a Windows Form with C Language? Only one window, not all Windows windows. Is it possible to also add a button to the title bar and control the action of that button? Thanks for supporting!
Hey. I'm kinda curious over your choice on windows as your environment is typical of Linux users. Does your development work rely on windows and windows' API ?
Most Linux systems have a default limit of 1024 file descriptors open for every process, so if there is a program with a severe resource leak problem, it could hit the limit and the OS will refuse requests for opening additional new files until anything is closed. Aside from this limit (say the limit is manually configured to be much larger), each resource takes up memory and if the leak is severe enough, it could eventually cause the process and the computer to be much slower. About the second question, when the process exits, the OS will cleanup all the remaining opened resources of the process.
my professors in university react allergic to gotos and im not allowed to use it due to "clean code reasons". is there a difference between using goto or a functioncall and return afterwards?
Gotos in general are indeed considered a bad practice since they can lead to spaghetti code, but specifically goto cleanup is a very good pattern in my opinion since it saves a lot of duplicate code and makes the code more readable and clean. There is indeed a difference between goto cleanup and a function call and return, since the cleanup has access to the same local variables, while calling a different function would require passing them each time
I really like, when instructors shows, how decipher a manual. As a C and an English learner, manuals are not written for starters. (a nonnegative integer). I think I would have written (a positive integer). I also think that Vim are for persons, who type well, so I'll stick with CodeBlocks. :o)
@@Michael-xq7vj As a non mathematical person, I think, zero is neither negative or positive. After a little search, I found a Wiki and I quote 'A negative number is always less than zero'. simple.wikipedia.org/wiki/Negative_number What do you think?
the use of labels and goto was a bit strange as its considered a bad practice, but I find that its quite powerful and it kinda just works when used properly.
Gotos in general are indeed a bad practice, but in my opinion when used specifically for cleanup as part of the "goto cleanup" pattern it is a good practice since it makes the code more readable and clean
Go to is hard choice, given the 4 decades of no no. Did have to use it in my system 370 mai frame programming and my first Basic. I wonder any other option. Obviously if the program exit it is not an issue. It is when the program or rather system is running where is the resource leak. Hence in this scenario when you said use 10 resources. 5 mem allocation on the heap and 5 file open. When one of file open failed, what should you do. You can no double close that file. But what other resources one has to handle. One way is to have a bool success as in the video. Success = false and for it a line where. Then continue … The last section will handle to close all resources fd -1 close it, not null pointer close it etc. then return 1 etc. Of course four function only non stack resources needed to be handled. What the goto avoid is the continue running part. In some case, you may want to do that to avoid say open 4 more files and allocate … or even worst interaction with user and write something etc. in the continue part. Unless every … has a check on success bool variable. Have some use I guess but never see it coming. Is it really common practice?
@@simpleprogrammingcodes * defer is same as its english meaning. * the statement u put after defer is automatically executed at the end of current block automatically. so, howsoever the current block ends, like inside an if, in a for loop, due to an error etc... the defer will get executed. * it alleviates u from putting it at every exit of the block. * so, u put the resource cleaning statement as a defer right after u allocated the resource. i don't have proper gut understanding of finally, but i guess yeah, u can maybe think of it like finally. > _"What is defer? Is it like garbage collector? Or like finally?"_
Yah i meant to also return after closing in the failure, but by mistake forgot, but anyway that was just an intermediate demonstration to get to the main point of using goto cleanup
💥💥💥😱😨😭🤮Hello Nir. As you know, I usually enjoy most of your videos, but this code example is one of the worst you presented here. GOTO is in general a recipe for failure, except of course for the rare programming languages with which you cannot write otherwise (Assembler for example). And not testing failure of your first file opening is also bad.I can deal with it, being old and weary but seasoned, but man, think of beginners, what crap habits and advice you are giving to newbies. It remembers me a first assembler program of yours in which you did not properly exited. Structured programming is a must, so please stick to it, and get rid of your GOTOs.
I never knew that "goto cleanup" was widely used in the linux kernel, so I guess it's definitely a credible pattern. The maxim, "goto considered harmful", is not as pervasive as I thought. If someone hates goto, I think a macro could achieve something similar to Python's with-statement contexts, that could be relatively neat, but, then, not everyone likes macro heavy C code. Other ideas would be to use a struct or some abstraction that holds all the resources and you pass it to a clean-up function at the end. So I guess the function caller creates the resource struct, passes it to the function, and the function can early return if it hits an error and the caller can pass the struct to a clean_up() function that does what it needs to do. Or maybe the program just uses system calls to get a list of file handlers that it has opened from Linux and deletes them. Of course, when a program closes all its file handlers should be automatically closed by Linux anyway.
@@Alex-kj9rc Not just goto cleanup--the kernel is replete with flow control gotos. In reality it's often the solution with the smallest footprint and fewest 'moving parts.'
@@freedomgoddess Yeah, Einstein, you really made the cleverest comment on YT, that you though funny. Except that it is not about getting out the most direct way of your spaghetti code, the point is coding the safest way, taught by best coders, not unknown people, after decades of programming.