logoalt Hacker News

Tharreyesterday at 4:30 PM2 repliesview on HN

It's worth noting that strcpy() isn't just bad from a security perspective, on any CPU that's not completely ancient it's bad from a performance perspective as well.

Take the best case scenario, copying a string where the precise length is unknown but we know it will always fit in, say, 64 bytes.

In earlier days, I would always have used strcpy() for this task, avoiding the "wasteful" extra copies memcpy() would make. It felt efficient, after all you only replace a i < len check with buf[i] != null inside your loop right?

But of course it doesn't actually work that way, copying one byte at a time is inefficient so instead we copy as many as possible at once, which is easy to do with just a length check but not so easy if you need to find the null byte. And on top of that you're asking the CPU to predict a branch that depends completely on input data.


Replies

ameliusyesterday at 5:00 PM

We should just move away from null-terminated strings, where we can, as fast as we can.

show 2 replies
samshineyesterday at 6:36 PM

I haven't seen a strcpy use a scalar loop in ages. Is this an ARM thing?

show 2 replies