logoalt Hacker News

ncrucesyesterday at 2:51 PM1 replyview on HN

I actually encountered it a couple weeks ago.

Can you spot the infinite loop in this function?

  char* strcpy(char* restrict d, const char* restrict s) {
    stpcpy(d, s);
    return d;
  }
I'll help. A call to `stpcpy` that ignores the return value can be swapped with a call to the (more likely to be optimized) `strcpy`. Since that's infinite recursion, and there is no forward progress, it's undefined behavior and anything goes.

This isn't just theory, it actually broke things in practice for me.


Replies

rssoconnortoday at 1:35 PM

Naming an externally linked function with the prefix "str" is by itself UB since that prefix is reserved for <string.h>.

show 1 reply