r/C_Programming 6d ago

Reliability Lessons From SQLite - Richard Hipp | SSW 2026

https://www.youtube.com/watch?v=V_qzqY1bb7I
37 Upvotes

15 comments sorted by

View all comments

Show parent comments

2

u/8d8n4mbo28026ulk 6d ago

If you want practical advice, for the above and any such code, just use an assert() and don't think about it. If predicate1() changes and p ends up being NULL, you want a loud signal that the code is buggy and you need to fix it.

Check for errors if the situation is truly recoverable from. If you try to open a file and that file doesn't exist, that's obviously a recoverable situation (and likely not your fault). What I mean is, it's an expected state that your program may enter. If p is NULL after predicate1(), that isn't at all a state your program is expected to be in, because you subsequently fetch ->x from it.

Here's a quote I like from Carmack:

A large fraction of the flaws in software development are due to programmers not fully understanding all the possible states their code may execute in.

If your code enters an invalid state, error-checking at runtime will generally not save you -- you have to fix the code. Use an assert() and perhaps abort() on release builds if you're really worried.

1

u/thradams 5d ago

I am writing a static analyzer, and I think the best approach is to move the assert from the caller into the function itself. However, we need a syntax for that. (just a sample)

bool  is_empty(struct X* p) 
   if (_R) {
      assert(p->a) ;
   }
   else 
   {
   };

Maybe natural language grammar? (looks natural but is grammar, not AI)

/*returns 
    true if the list is empty. In this case plist->hread is not null
    otherwise return false and plist->head is not null.
*/
bool  is_empty(struct list* plist);

The idea is that, if I change the function is_empty changed the contract, the places are using the information will not override the assert. they will use the assert that is part of the contract.

Why not C++ contracts? I don't like the idea of individual and independent contracts-predicates. Normally the function contracts are like the sample I wrote.. and we have pos conditions that are related to function result.