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

`malloc(3)`. Many of the functions in string.h.



Yeah there are a couple of (3) functions (i.e. not syscall interfaces) that return pointers. It's very common for those to return NULL on error, hardly a surprise. It will also blow up with a segfault should you forget to check success.


> It will also blow up with a segfault should you forget to check success.

My guess is this is usually true in practice, but in C and C++ dereferencing a null pointer is UB so you really can't assume that.


You shouldn't intentionally rely on a segfault as a means of terminating the program -- do sth. like `exit(1)` instead.

What I'm saying is there isn't an ergonomic issue with NULL error return APIs. You might prefer algebraic error types (in other languages). I'm not even sure I do. NULL return APIs are clean and simple. If you do (accidentally) forget to check for NULL return code, you will for sure get a segfault on first access in practice (not on embedded platforms maybe). The compiler can't remove any following code unless it can prove only NULL will ever be returned. Don't fall trap to UB FUD.


> The compiler can't remove any following code unless it can prove only NULL will ever be returned.

It can reorder code, though. For example, it can change

  int *x = malloc(sizeof(int));
  *x = 42;
  if (x)
      launch_the_nukes();
to

  int *x = malloc(sizeof(int));
  launch_the_nukes();
  *x = 42;


The compiler can only reorder when that would be ok in the absence of UB. What can be reordered before the write through the pointer can't read the pointer, and can't really do any damage. Syscalls and library calls (in particular if dynamically linked) can't be reordered before the write because the compiler can't see what the do.

Most of the UB FUD are contrived examples that hardly happen in practice. What I'm saying is not that you should write bugs, but that bugs (especially segfaults) will immediately turn up in practice.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: