Scary Functions: rawmemchr

Recently I received a bug report for psmisc that basically supplied a patch so psmisc works in a cygwin environment.  Nothing terribly exciting in that and the changes are pretty uncontroversial.

One of the changes is in that instead of using rawmemchr to find the end of the string, cygwin doesn’t have that function and so it is replaced by strchr.  I’ve not seen the function rawmemchr before so I had a closer look.

Initially I was a little worried, rawmemchr tries to find the given byte starting at a given pointer but unlike strchr it doesn’t stop unless it finds the character. I think the only time this function is safe, or is no more evil than anything else, is when you are searching for the NUL character which is what fuser in psmisc does.

Still, the string being checked is coming from getcwd which requires a string or buffer length so perhaps it would be better to use memchr which is a little slower but has a maximum length parameter.  If you have code that uses this function, you may just want to check how it is being used because it seems like an old bad gets function that plagued a lot of programs.

Enhanced by Zemanta

3 thoughts on “Scary Functions: rawmemchr

  1. I learned something today: that strchr(s, 0) doesn’t simply return NULL. The C standard says so explicitly, while the linux manpage I have isn’t specific enough.

    If I’d followed the linux manpage to implement strchr, I doubt that I’d have gotten this behavior right.

  2. Please ask cppcheck upstream to add a check for improper or unsafe use of rawmemchr.

  3. … why not simply use strlen()?

    I think you’re right about rawmemchr, though; it looks like someone in the bad old days, when GNU would just make extensions up, thought they could save a few cycles at the expense of safety.

Comments are closed.