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