The Importance of Error Handling in C

  Рет қаралды 32,253

Nir Lichtman

Nir Lichtman

Күн бұрын

Пікірлер: 122
@pavfrang
@pavfrang Жыл бұрын
Your video is GREAT! I would only comment that it would be preferable to print to stderr instead of stdout (printf), for critical errors that terminate the application. So, you should use fprintf(stderr, ...) instead. The main reason for this, is that different redirection is typically done for stderr and stdout - the user might want to handle error messages differently from the informational messages.
@nirlichtman
@nirlichtman Жыл бұрын
This is a great point, thanks!
@ilmannen
@ilmannen Жыл бұрын
Another suggestion is to use perror (also prints to stderr), which provides the message from the errno to the user without them having to look it up.
@rian0xFFF
@rian0xFFF Жыл бұрын
I just use perror()
@blacklistnr1
@blacklistnr1 Жыл бұрын
I've felt the lack of a separate error channel because I thought "just put everything into stdout, so much easier!" in a project: * the stdout quickly became unreadable and broke formatting * it also broke the REPL which was using stdin/out => errors needed special integration to be readable so "just put errors into stderr, so much easier!" :))
@pavfrang
@pavfrang Жыл бұрын
yep perror the same, I just wanted to emphasize writing to stderr@@ilmannen
@rocknowradio
@rocknowradio Жыл бұрын
"That is because C does not come with built-in exception support". Thanks God for that.
@sputnick1
@sputnick1 Жыл бұрын
Great video! this is actually a big issue i certainly had in my first few c programs before i had enough experience to know better. One thing to note is the perror function. If you call perror, not only will it print to stderr (always print to stderr instead of stdout for errors), but it will also give you a description of the error number encountered. (the same text from the errno command)
@johnshaw6702
@johnshaw6702 Жыл бұрын
Thanks for presenting this. One of the things that always botherd me is progaming books that say they are leaving out the error checking to simplify the code for understanding, which it does, was that they often leave out a section on proper error checking and handling. When I first taught myself programming, I did a lot of research and reading (before the internet). I didn't fully trust anything and made sure that if my program failed it didn't crash the system, barring a system/hardware failure. Then modern systems like Windows came out and all bets were off. I could still write good code, but now I was more dependent on the Windowing system to not introduce errors, like memory leaks that forced me to write work arounds.
@uberbaud
@uberbaud Жыл бұрын
Instead of calling gcc or clang directly, you can call 'make prog' and it will compile prog.c using environment variables CFLAGS LDFLAGS and LDLIBS. No Makefile required. You can see exactly the calls make will use with 'make -p'. One benefit is no a.out, and it's usually less typing.
@erc0re526
@erc0re526 Жыл бұрын
Its amazing that it works. Now I must ask, how did you find this out? I didn't see any mention of it in the manpage... Thank you for this tip!
@uberbaud
@uberbaud Жыл бұрын
@@erc0re526 In the opening paragraph of OpenBSD's make(1) man page, it says, " If neither of these exist, make can still rely on a set of built-in system rules." One of the many reasons I like OpenBSD is the quality of its documentation. Notably, GNU make has the same behavior but their manpage incorrectly states that "you must write a file called the makefile".
@erc0re526
@erc0re526 Жыл бұрын
@@uberbaud One more reason for me to try OpenBSD! That's fascinating. Thank you
@kinershah464
@kinershah464 8 ай бұрын
So much cool information. Very important error handling, right error handling with right tools and you can avoid hours of debugging an issue.
@michaelhohmann2868
@michaelhohmann2868 Жыл бұрын
I really appreciate your focus on important and interesting information. There is no unnecessary spam and begging for likes and subscriptions. I immediately liked and subscribed 8-)
@alielmessaoudi4863
@alielmessaoudi4863 Жыл бұрын
Very valuable and interesting content, can't stop watching your videos, absolute value here
@imod5
@imod5 Жыл бұрын
I am currently working on an actual c program for the first time and this video showed in my home page at the right time. Thanks!
@johnshaw6702
@johnshaw6702 Жыл бұрын
Check everything unless you know for a fact it can't fail and even then you may want to check. If you're not sure about something, look it up and verify. I self taught myself in the late 80's and early 90's and always double checked everything. Return values are there for a reason. Programmer's mantra: Trust but Verify.
@imod5
@imod5 Жыл бұрын
@@johnshaw6702 That is a very valuable tip. Thank you for sharing!
@mohammedsalman3397
@mohammedsalman3397 Жыл бұрын
If you're on vim you can do shift-K to bring up the manual for the function your cursor is on
@nirlichtman
@nirlichtman Жыл бұрын
That is a cool tip, thanks! Just notice that it opens on full screen and so if you want to open the manual in split screen you can either use the :term like I do in the video or the :Man vim command which opens the manual as a Vim buffer
@darknais
@darknais Жыл бұрын
man thats a god hack!! in my coding campus we dont have access to internet during exam only man pages this going to save me some time!
@mohammedsalman3397
@mohammedsalman3397 Жыл бұрын
@@nirlichtman Yeah, forgot that it takes over the entire screen by default 😅I use neovim which opens the man page in a split window which I assume it's not impossible to do in vim.
@steveoc64
@steveoc64 Жыл бұрын
Be interesting to do a retake of this using zig, as it’s a good demo of how zig applies error handling to existing C idioms, without adding a tonne of boilerplate or weird abstractions. The error backtrace is particularly handy as well.
@r3v0lv3rz
@r3v0lv3rz Жыл бұрын
Very clear and a great explanation of all concepts on your part. Thanks.
@Jonathan-ru9zl
@Jonathan-ru9zl 11 ай бұрын
Hi Nir. Thanks for the videos 🙌 Do you recommend using Linux over Windows OS?
@nirlichtman
@nirlichtman 11 ай бұрын
Whatever you find most comfortable, I like using Windows as my main OS and Linux through WSL
@Jonathan-ru9zl
@Jonathan-ru9zl 11 ай бұрын
@@nirlichtman I don't get it why people are still using Linux as their main OS (And saying that it is better than Windows)? Let me explain my point of view (Related to Ubuntu mostly): 1. Linux OS is asking for the password every once in a while, approx. 100 times a day, wasting a bunch of time. If you're not lucky, Linux can't detect even the right password Isn't it archaic and stupid? 2. Linux isn't compatible with many software programs and drivers 3. It is a command base OS - you have endless shortcuts and commands which are impossible to remember 4. End of life after couple of years, which requires you to install a new version 5. GUI in Windows is extremely better I'm embedded developer, so I am using Linux only because I have to, but for my daily use, I'm happy with Windows
@nirlichtman
@nirlichtman 11 ай бұрын
@@Jonathan-ru9zl Yah my main reasons for preferring Windows as my main OS is the compatilibilty and that I like the user interface and am very familiar with it, and now that there is WSL there is not really a reason for me to switch to Linux, but i like using Linux distros for server side since they mostly have low hardware requirements and are comfortable for those kind of stuff
@Offdopp
@Offdopp 6 ай бұрын
There's just nothing better than Linux for C development, is all. On Linux you have easy access to your choice of package manager, which will automatically handle any and all dynamically linked libraries. Additionally, software is so much easier to install with this method. Oh, and the filesystem(s), system calls, and kernel are all just better than what Windows has to offer. If you want to write software without learning new things, use MacOS Edit: There's good things to say about the OS as a whole, but both Mac and Linux listen to the Unix philosophy, which makes my life as a developer sooooo much simpler.
@Jonathan-ru9zl
@Jonathan-ru9zl 6 ай бұрын
@@Offdopp Windows gui experience is much better, at least for the average user And today, I think Windows come up with many alternatives for Linux packages and libraries And btw, how do you handle typing your password again and again on Linux?
@StefanWelebny
@StefanWelebny Жыл бұрын
Again valuable content. And thank you very much for answering my question about port connection concurrency regarding your last video!
@SuborbitalSentinel
@SuborbitalSentinel Жыл бұрын
Do you have any videos on your dev setup? I'm interested in how you are running what looks like dwm and the windows terminal?
@nirlichtman
@nirlichtman Жыл бұрын
My welcome link in the channel description contains info about my setup, I also have a video about this on my channel
@UliTroyo
@UliTroyo Жыл бұрын
Your C videos are so good! Thanks!
@meni181818
@meni181818 Жыл бұрын
instead of initializing the whole buffer with zeros you can set the last char of it to zero: #define BUF_LEN 256; char buffer[BUF_LEN]; buffer[BUF_LEN - 1] = '\0'; thanks for your content!
@eitantal726
@eitantal726 Жыл бұрын
Then your buffer is filled with garbage (former stack data) except the last char. You merely ensure that if an un-initialized char buffer is used, it will stop at the end at least. I wouldn't recommend this technique unless CPU time is so critical that "whatever = {0};" is too expensive
@meni181818
@meni181818 Жыл бұрын
@@eitantal726that is the main reason.
@nirlichtman
@nirlichtman Жыл бұрын
@@eitantal726 I agree with Eitan on this point, it is a good practice to always ensure that you are working with all zeroed buffers or else it can lead to weird bugs
@anon_y_mousse
@anon_y_mousse Жыл бұрын
I didn't even know there was an errno program. I thought maybe you wrote it yourself but looked it up and found it in moreutils. I'll have to recommend this to anyone learning C.
@acdimalev8405
@acdimalev8405 Жыл бұрын
These days, rather than prototyping without error handling I lean into explicitly terminating the program. void _panic(int line) { printf("PANIC: %d ", line); exit(-1); } #define panic _panic(__LINE__) This helps with finding problems early without littering the program with boilerplate, and later it's useful for identifying places that I may want to add additional error handling logic. As a side bonus, it's also an active deterrant against internalizing an active ignorance of error handling. With how much time I spend prototyping, it's foolish to think it will be easy to mode-switch out of the habits I develop while prototyping.
@gblargg
@gblargg Жыл бұрын
2:40 Set your command prompt to show when a command failed, and its code. Makes it easier to spot failed commands in interactive sessions.
@cyrilemeka6987
@cyrilemeka6987 Жыл бұрын
How?
@gblargg
@gblargg Жыл бұрын
@@cyrilemeka6987 See "Bash prompt with the last exit code" (assuming you use Bash).
@raccoon1160
@raccoon1160 Жыл бұрын
Great video, I see way too much code that just ignores errors. Zero initializing (char buf[256] = {0}) is also standard in C89
@gblargg
@gblargg Жыл бұрын
Then there's code that lumps all errors together. Disk full? Read-only filesystem? Out of memory? File not found? User value out of range? All the same error reported to the user!
@niki7968
@niki7968 Жыл бұрын
I have a quick question. Why do you use the windows terminal, or at least riced some other terminal to look like the window's one, on linux? Is it just for the laughs?
@nirlichtman
@nirlichtman Жыл бұрын
I am using Windows as my main OS and a dwm port for Windows, more info about my setup in the channel description
@grimvian
@grimvian Жыл бұрын
For a immediately C coder like me, it's a great topic to incorporate error handling the correct C way. And a big thanks for not using music and not using disturbing video editing. May I ask, why you kind of do advertising for a Chinese brand?
@nirlichtman
@nirlichtman Жыл бұрын
Are you referring to my hostname with "lenovo" in it? that is not part of any advertising on purpose, it's my laptops name for many years, but indeed it is a good idea now to change the name didn't think about this, thanks for the feedback :)
@grimvian
@grimvian Жыл бұрын
@@nirlichtman Yes I am and just what i thought. Now retired reseller and had installed thousands of Windows computers, by wiped out everything on the hard drive. I just installed a clean system and minimum of drivers. Now it's Linux Mint LMDE and C programming with Code::Blocks. Keep up the great work.
@aah134-K
@aah134-K Жыл бұрын
Very amazing videos, what a treasure
@AK-vx4dy
@AK-vx4dy Жыл бұрын
What are you using with this numerated tabs on top ?
@Not_Even_Wrong
@Not_Even_Wrong Жыл бұрын
Thanks. I need to learn more about this, even good books don't convert it at all.
@NecdetSanli
@NecdetSanli 11 ай бұрын
How did you split your terminal? Do you use vim as editor?
@nirlichtman
@nirlichtman 11 ай бұрын
Yes I use Vim and I split using the built in windowing, for more info I have a video about cool window splitting features on Vim
@umairmuhammadabbas3929
@umairmuhammadabbas3929 Жыл бұрын
Thanks for sharing this information
@m0zart-l3q
@m0zart-l3q Жыл бұрын
Hi Nir, I watched most of your videos and I liked your projects very much. So I want to learn how do you improved yourself so much in low-level programming.
@nirlichtman
@nirlichtman Жыл бұрын
Thanks! What helped me the most with learning low level is to make my own projects and play around with various linux/windows api calls, for example one of my projects was a c++ web server that stored messages that i sent it, another thing that helped me was to contribute to open source projects which is a great way to learn how to work with a lot of existing code and to use the debugger effectively.
@Abhishek-pp8ck
@Abhishek-pp8ck Жыл бұрын
​@@nirlichtmanHello Nir sir, i also want to learn linux/C/Networking, where do i start? do you know any resources....?
@nirlichtman
@nirlichtman Жыл бұрын
@@Abhishek-pp8ck the best way to learn in my opinion is to make your own projects in c and work with the man pages alongside to learn about the os functions, for example an idea for a networking project in c can be a web server and client, or maybe an online simple game, for a general guide on networking i remember beejs guide to networking as good
@BSPNode
@BSPNode Жыл бұрын
Before I get into this, shouldn’t main return an integer? Also I see you dereferencing the “strrchr” function, but I didn’t even know that was possible. Can anyone explain if this is valid C?
@Not_Even_Wrong
@Not_Even_Wrong Жыл бұрын
You're correct. When I have time I'll compare the assembly and see what or IF the compiler does anything differently. This is why C is so insane... Why not just throw a 'this is wrong learn C' error? No the compiler just does 'something '.... Smh
@nirlichtman
@nirlichtman Жыл бұрын
Actually, returning void from main is completely valid C :) According to the documentation, since C99 the main entry point can return void and this means the program exit code is undefined devdocs.io/c/language/main_function About the deref of strchr, it also valid C, but as I explain later in the video, it is recommended to check if it failed before derefing it
@BSPNode
@BSPNode Жыл бұрын
@@Not_Even_Wrong Fair enough, I'm mainly a Windows programmer, so seeing how "void main" is legal confused me a bit. After a minute of research, a lot of the C++ people hate the idea of "void main", and require programmers to use "int main" instead.
@BSPNode
@BSPNode Жыл бұрын
​@@nirlichtman Learn something new every day :) - I'm mainly a computer graphics programmer, so I don't know how I got here, but great video though!
@Not_Even_Wrong
@Not_Even_Wrong Жыл бұрын
@@nirlichtman okay it's valid in the sense that unspecified in C means implementation defined. It can always return 0 or 1 or whater BUT the compiler has to decide. In contrast to undefined which means nobody has to decide... This is the part of C that I don't like... Thanks for replying either way. Taught me once again to not trust stackoverflow...
@ayushmaanshrotriya3677
@ayushmaanshrotriya3677 Жыл бұрын
Hey. Can you do a video on c based project like creating heap memory manager??
@greyfade
@greyfade Жыл бұрын
Why are you printing the errno with printf? Use `perror(3)`. It will print the error string to stderr (which is what you should be doing), so you don't have to use errno on the command line. This is better for users and better for logging.
@nirlichtman
@nirlichtman Жыл бұрын
Right, totally agree, that was a mistake
@nno64209
@nno64209 Жыл бұрын
Can you make a window tutorial with assembly, please ?
@nirlichtman
@nirlichtman Жыл бұрын
You mean opening a window with Assembly? Or Windows the OS?
@ryku112
@ryku112 Жыл бұрын
hi how do you find the functions with man,when i try it it doesn't work
@nirlichtman
@nirlichtman Жыл бұрын
You can get the dev man pages with your package manager, if you are using Debian/Ubuntu you can run apt install manpages-dev, more info about my setup in the channel description link
@ryku112
@ryku112 Жыл бұрын
@@nirlichtman tysm
@ItsCOMMANDer_
@ItsCOMMANDer_ Жыл бұрын
Another good example is yohttps srrver video, after the ser er has been used once (at leadt for me) bind() will fail the next time with return code - 1. I dobt want to blame you , this might be a problem with my wsl setup. But without debug printing the return values, i would have never kniwn that bind was the reason the server only works sometimes
@nirlichtman
@nirlichtman Жыл бұрын
Your comment on that vid was indeed one of my inspirations for making this video :) Bind indeed can fail sometimes if you run it again on the same port not long after the previous run has finished (my guess is that it is due to some OS used ports cleanup that has not happened yet)
@ItsCOMMANDer_
@ItsCOMMANDer_ Жыл бұрын
most likely true, because errno returns 0.@@nirlichtman
@bigapple89
@bigapple89 Жыл бұрын
Could you make a video on creating a simple email server? Thanks anyway!
@Benjaneb
@Benjaneb Жыл бұрын
It looks like you're running dwm on Windows, how is that possible?
@nirlichtman
@nirlichtman Жыл бұрын
I am using a port for Windows, the welcome link on my channel desc contains additional info
@styx2084
@styx2084 Жыл бұрын
do you use DWM in windows?
@nirlichtman
@nirlichtman Жыл бұрын
yes, more info on the welcome link on my channel description
@nathanthompson506
@nathanthompson506 Жыл бұрын
this was brilliant. thanks
@AdventuresOfPepero
@AdventuresOfPepero Жыл бұрын
wait! wait! you are inside windows?! how did you use dwm inside windows?
@nirlichtman
@nirlichtman Жыл бұрын
check out the welcome link in the channel description :)
@darknais
@darknais Жыл бұрын
Thanks for the video!
@guilherme5094
@guilherme5094 Жыл бұрын
👍👍Thanks!
@jochen_schueller
@jochen_schueller Жыл бұрын
Yeah, very important, but can also be done later
@masterbedroom594
@masterbedroom594 Жыл бұрын
Hi Nir, how are you? Are you safe?
@nirlichtman
@nirlichtman Жыл бұрын
My country is going through complicated times, but I am safe, thanks
@alister_
@alister_ Жыл бұрын
@@nirlichtman Where are you from? :\ Wish you the best.
@nirlichtman
@nirlichtman Жыл бұрын
@@alister_ thanks, I am from israel
@OlliS71
@OlliS71 Жыл бұрын
Better use RAII and Exceptions (here system_error) with C++. Much less work.
@robertolin4568
@robertolin4568 Жыл бұрын
Without error handlings, we live with the shell scripts.
@sbef
@sbef Жыл бұрын
Instead of that printf that prints a numeric errno, you can just use perror.
@its_code
@its_code Жыл бұрын
❤❤❤❤❤❤😊
@AlaskanInsights
@AlaskanInsights 8 ай бұрын
another good reason is the use of void main.... errrrr
@smylesg
@smylesg Жыл бұрын
I guess I would start by checking s != -1. No point in building structures or making other calls unnecessarily.
@otaxhu
@otaxhu Жыл бұрын
I did not know about errno header file
@xBiggs
@xBiggs Жыл бұрын
void main lul
@kamertonaudiophileplayer847
@kamertonaudiophileplayer847 Жыл бұрын
Rust uses a similar error handling, but you can skip it, you have to explicitly say - ignore an error.
@DK1PL
@DK1PL Жыл бұрын
The Importance of Error Handling in C: I have expected some ideas of sophisticated error handling in C and I found just a basic of the return value handling as on first page of the C language tutorial. 👎
@swedishpsychopath8795
@swedishpsychopath8795 Жыл бұрын
FAKE TUTORIAL: At 2:27 if you stop the video and microstep back and forth (with dot and comma) you can spot the compile error he didn't want us to see.
@nirlichtman
@nirlichtman Жыл бұрын
Actually, the tutorial is completely real - that is a compiler warning, not an error (the warning is related to the address structure - this is not related to the point of the video anyway) and I am completely fine with you seeing it, it appears for more than a microstep no need for dot and comma.
@LabiaLicker
@LabiaLicker Жыл бұрын
ayo hold up. your seriously using the edge browser? 💀
Arenas, strings and Scuffed Templates in C
12:28
VoxelRifts
Рет қаралды 106 М.
the cleanest feature in C that you've probably never heard of
8:13
VIP ACCESS
00:47
Natan por Aí
Рет қаралды 30 МЛН
Quando A Diferença De Altura É Muito Grande 😲😂
00:12
Mari Maria
Рет қаралды 45 МЛН
小丑教训坏蛋 #小丑 #天使 #shorts
00:49
好人小丑
Рет қаралды 54 МЛН
“Don’t stop the chances.”
00:44
ISSEI / いっせい
Рет қаралды 62 МЛН
Global Error Handling in C# Minimal APIs
13:59
IAmTimCorey
Рет қаралды 18 М.
Handling Errors in C/Unix (perror, strerror, errno)
6:36
Jacob Sorber
Рет қаралды 39 М.
The secret to making Golang error handling a breeze
13:46
Earthly
Рет қаралды 14 М.
Making Smallest Possible Linux Distro (x64)
27:43
Nir Lichtman
Рет қаралды 148 М.
Making Minimalist HTTPS Server in C on Linux
16:11
Nir Lichtman
Рет қаралды 21 М.
Making a Very Minimal Windows Executable in C
7:48
Nir Lichtman
Рет қаралды 96 М.
you need to stop using print debugging (do THIS instead)
7:07
Low Level
Рет қаралды 467 М.
How Linux Kernel Runs Executables
16:46
Nir Lichtman
Рет қаралды 60 М.
Adding Simple System Call in Linux Kernel
7:44
Nir Lichtman
Рет қаралды 20 М.
How C++ took a turn for the worse
5:03
Code Persist
Рет қаралды 339 М.
VIP ACCESS
00:47
Natan por Aí
Рет қаралды 30 МЛН