Hacker News new | past | comments | ask | show | jobs | submit login

I know, that's why I have these:

http://c.learncodethehardway.org/book/ex20.html

But, when talking about this I didn't want to muddy the waters with my own assert alternatives. Programmers have a hard enough time focusing on the issue of a for-loop vs. a while loop.

Edit: malloc returning NULL means you're out of heap. That's usually catastrophic in almost all cases, but the important part is that people don't detect that, then use the NULL pointer. That's the bug.




In a chapter about deconstructing someone else's book, your own book also does dangerous things according to yourself:

> The problem is, as with every book with code ever in the universe, beginners will copy that code out and use it somewhere else and then the function is wrong.

Yet, if a beginner copied some of the code in this chapter they'd have the exact bug you are talking about here (using the NULL pointer returned from malloc()).

I think you should probably expand that into the safer checks (don't forget to free(line) if longest is NULL too!).


Are we looking at the same code? I use an assert to quickly check for NULL, and this is a simple example of how to work with the function. Other parts of the book use more extensive error checking and I use my debug.h macros quite a lot, but if you find bugs feel free to email me them. I'd really appreciate it.


I'm referring to this code on the originally linked page [1] (you'll have to scroll back a bit because your header blocks the content).

In the context of this thread, brghts states that this is dangerous because if you compile with -DNDEBUG the assert is optimized away.

So if I copy that code with the assert statement, it will be optimized away and your code no longer performs the NULL check. This is bad.

As you mention, beginners tend to copy code off the Internet and cause bugs. If you recognize this and claim to be teaching people you should not use bad practices in your example code. Period.

If you don't want to muddy the waters with your custom debug macros, then you should still play it safe when checking return values the a beginner may simply copy and think is correct.

[1]: http://c.learncodethehardway.org/book/krcritique.html#code--...


The "if (temp) free(temp);" line made me chuckle.


Can I ask why? Is it bad style? (I'm fairly new to C)


I'm late to the party here, but `free` is a no-op on a null pointer. So checking for null is just duplicating the first thing `free` does.




Consider applying for YC's W25 batch! Applications are open till Nov 12.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: