PHP is often just bland drudge, true horror in PHP land is unexpected when I encounter it.
But when it does surprise you, it's almost never anything good. Stuff like Duff's device, `3[someArray] = value`, etc. The surprises are always the language's raw machinery showing through in unpleasant ways, and never a delightful bonus feature the designers added for you.
I was reading "Writing Solid Code" by Steve Maguire (though it should really be called "how to write code in C without shooting yourself in the foot"). One thing that surprised me, but which made sense, was that pointers can overflow. It's unlikely, and ANSI non-compliant, but something possible nonetheless. Hence, Maguire said that this code:
void *memchr(void *pv, unsigned char ch, size_t size)
{
unsigned char *pch = (unsigned char *)pv;
unsigned char *pchEnd = pch + size;
while (pch < pchEnd)
{
if (*pch == ch)
return (pch);
pch++;
}
return (NULL);
}
Has a bug. It surprised me when reading it, because it's such a common language idiom."What range of memory would memchr search when pv points to the last 72 bytes of memory and size is also 72? If you said 'all of memory, over and over,' you're right. Those versions of memchr go into an infinite loop because they use a risky language idiom—and Risk wins."
So, he said that that code should be replaced with this code:
void *memchr(void *pv, unsigned char ch, size_t size)
{
unsigned char *pch = (unsigned char *)pv;
while (size-- > 0)
{
if (*pch == ch)
return (pch);
pch++;
}
return (NULL);
}
Just the little things C lets you think about. This seems like a bug that would occur every once in a blue moon.Not always. It's rare, but eg `o[objects].up[objects].t[textures]` was definitely a delightful bonus feature (where `objects` and `textures` are global arrays).