Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

No, the problem with null is the inability to enforce, at the type level, that a particular value is not null. C simply does not have a type for "guaranteed valid pointer to x".



C allows defining new types though, so it can be done.


It can only really be done on a per codebase level, really.

By which I mean, in my highly sensitive and correct program xyz I can (say) abstract all access to a type (A struct?) through a macro which would contain null checking/assert-ing. This could work perfectly well and even be static checked for (in principle).

However, if I tried to package this type up in a library it all basically falls flat - or at least it would be very easily broken.

Doing this like this is to static analysis(/The Type system) as foreplay is to sex.


Unless I'm misreading OPs statement, it can't be done by defining a new type since C (unlike, say, Ada) doesn't support subrange types.


Could you provide an example? Either source code or a link. I want to see how you might define a type for "guaranteed to not be null pointer to char".


I'm thinking of just:

    struct char_nonnull_t { char *ptr; };

    char *char_nonnull_as_pointer(struct char_nonnull_t cp) { return cp.ptr; }
With the required extra accessor functions. Of course in C, we don't have generics, data hiding or other nice features, so we have to build a wall of conventions around our types instead. Types with invariants are totally possible in C. We just don't have a way to automatically enforce them. It's C, after all.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

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

Search: