Тёмный

The Importance of Resource Cleanup in C 

Nir Lichtman
Подписаться 44 тыс.
Просмотров 6 тыс.
50% 1

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")

Наука

Опубликовано:

 

6 мар 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 66   
@nirlichtman
@nirlichtman 3 месяца назад
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.
@anon_y_mousse
@anon_y_mousse 3 месяца назад
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.
@carlossaenz8204
@carlossaenz8204 3 месяца назад
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
@yash1152
@yash1152 3 месяца назад
but he dd already ig
@nirlichtman
@nirlichtman 3 месяца назад
Yah i have a vid on man pages tips :)
@benxxiao
@benxxiao 3 месяца назад
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.
@boy_deploy
@boy_deploy 3 месяца назад
This is why I love Zig's defer keyword. Awesome content 🎉
@redcrafterlppa303
@redcrafterlppa303 3 месяца назад
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.
@jenselstner5527
@jenselstner5527 3 месяца назад
Yessss, at last: A programmer using goto the way I do. This is usful for not have to copy & paste the exit clean-up code all over the place.
@cocusar
@cocusar 3 месяца назад
I'm a big advocate of using goto cleanup, after working with kernel stuff, you tend to naturally create the code following the pattern!
@dtikvxcdgjbv7975
@dtikvxcdgjbv7975 3 месяца назад
Nice work.
@angelffg
@angelffg 3 месяца назад
Nice video!
@accountname4442
@accountname4442 3 месяца назад
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.
@nirlichtman
@nirlichtman 3 месяца назад
Yah I will make one for Win as well :)
@guilherme5094
@guilherme5094 3 месяца назад
👍👍Thanks!
@caiomadeira9293
@caiomadeira9293 3 месяца назад
Great video! Do you intend to cover c consoles (in general)?
@nirlichtman
@nirlichtman 3 месяца назад
Thanks! What do you mean by C consoles?
@angelffg
@angelffg 3 месяца назад
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!
@arma5166
@arma5166 3 месяца назад
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 ?
@nirlichtman
@nirlichtman 3 месяца назад
Yes I do both Linux and Windows dev, and also like using Windows as my main OS for various additional reasons (more info in welcome link)
@bayzed
@bayzed 3 месяца назад
Why would a resource leak be a problem? And what happens to the opened resources after the process exits (assuming we didn't manually close it)?
@nirlichtman
@nirlichtman 3 месяца назад
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.
@RealYukiSan
@RealYukiSan 3 месяца назад
I heard from someone that goto considered harmful, but I don't know and wondering why?
@omeg666
@omeg666 3 месяца назад
It can lead to unreadable code if overused. This here is a good example of how goto can be properly used.
@anonymouscommentator
@anonymouscommentator 3 месяца назад
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?
@nirlichtman
@nirlichtman 3 месяца назад
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
@anonymouscommentator
@anonymouscommentator 3 месяца назад
@@nirlichtman thanks for the explanation!
@pugo7925
@pugo7925 3 месяца назад
Thsnks for the video, I wonder why use goto and not jsut another function ?
@yash1152
@yash1152 3 месяца назад
u need to pass all variables to another fxn
@orychowaw
@orychowaw 3 месяца назад
A similar approach is used with "goto error"
@grimvian
@grimvian 3 месяца назад
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
@Michael-xq7vj 3 месяца назад
nonnegative includes zero, positive doesn't
@grimvian
@grimvian 3 месяца назад
@@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?
@grimvian
@grimvian 3 месяца назад
@@Michael-xq7vj Wiki says negative numbers are less than zero.
@Michael-xq7vj
@Michael-xq7vj 3 месяца назад
@@grimvianthat's right! 👍 so what are nonnegative numbers? (hint: they are NOT greater than zero... that would be positive numbers...)
@grimvian
@grimvian 3 месяца назад
@@Michael-xq7vj English is obvious my second language, but as I understand, you are contradicting yourself...
@rian0xFFF
@rian0xFFF 3 месяца назад
Does valgrind catch this kinda of leak, doesn't?
@nirlichtman
@nirlichtman 3 месяца назад
Haven't tried, but could be interesting to cover in a future vid
@HomeofLawboy
@HomeofLawboy 3 месяца назад
Goto cleanup feels like a return with extra steps, very useful pattern.
@Brad_Script
@Brad_Script 11 дней назад
it's basically the "finally" block in a try/catch/finally
@mouseroot8053
@mouseroot8053 3 месяца назад
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.
@nirlichtman
@nirlichtman 3 месяца назад
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
@kwccoin3115
@kwccoin3115 27 дней назад
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?
@kwccoin3115
@kwccoin3115 27 дней назад
Btw easier may be to have a pointer array to the resources and loop it … :-)
@yash1152
@yash1152 3 месяца назад
yeah, i wont use a manual managed language without defer.
@simpleprogrammingcodes
@simpleprogrammingcodes 16 дней назад
What is defer? Is it like garbage collector? Or like finally?
@yash1152
@yash1152 15 дней назад
@@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?"_
@simpleprogrammingcodes
@simpleprogrammingcodes 15 дней назад
@@yash1152 Thank you!
@rocknowradio
@rocknowradio 3 месяца назад
close(fd) twice is a bug.
@nirlichtman
@nirlichtman 3 месяца назад
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
@rocknowradio
@rocknowradio 3 месяца назад
I imagined, you did not want to do the video all over just for this :)
@yogxoth1959
@yogxoth1959 3 месяца назад
The volume on this video is really low, fyi.
@nirlichtman
@nirlichtman 3 месяца назад
Interesting, thanks for the information will work to improve for next ones 👍
@oop1761
@oop1761 3 месяца назад
Hi 😂
@nirlichtman
@nirlichtman 3 месяца назад
Hi :)
@DanielPetre
@DanielPetre 3 месяца назад
you're -19 db.. boost or normalize your voice over dude
@Argon32
@Argon32 3 месяца назад
💥💥💥😱😨😭🤮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.
@ax13h
@ax13h 3 месяца назад
Sometimes goto is the best solution. If you think there's a better "structured" solution to handling nested resources then could you provide it?
@Alex-kj9rc
@Alex-kj9rc 3 месяца назад
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.
@ax13h
@ax13h 3 месяца назад
@@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
@freedomgoddess 2 месяца назад
​"the most direct way to go somewhere is 'goto'." - unknown
@Argon32
@Argon32 2 месяца назад
@@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.
Далее
How to Call Assembly Code from C
3:46
Просмотров 28 тыс.
The Importance of Error Handling in C
8:18
Просмотров 29 тыс.
При каком ВЕСЕ ЛОПНЕТ ШИНА?
18:44
Making Minimalist Web Server in C on Linux
10:23
Просмотров 229 тыс.
Reverse Engineering Simple Windows Driver
12:09
Просмотров 7 тыс.
30 Beginner Vim Commands in 7 Minutes
7:13
Просмотров 9 тыс.
Linux named and unnamed pipes
6:02
Просмотров 156
why do header files even exist?
10:53
Просмотров 369 тыс.
Making Minimalist Snake Game in C on Linux
8:01
Просмотров 28 тыс.
Are headphones destroying our hearing?
6:49
Просмотров 236 тыс.
Adding Simple System Call in Linux Kernel
7:44
Просмотров 13 тыс.
Making Simple GUI Window in C on Windows
18:20
Просмотров 23 тыс.
Все розовые iPhone 💕
0:51
Просмотров 225 тыс.