Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

So does anyone know of a good list of "worst practices" when coding in C? Basically usage that results in undefined behavior which can come back to bite you when run on another architecture?

For example, doing a strcpy(dest, dest + 1) will work in most cases, but if done on 64-bit Linux with a CPU that has sse4 optimizations, you will get random corruption on certain string lengths. (The C standard says that the behavior in this case is undefined). I'd like to see a list of items such as this to watch out for when auditing code.



https://www.securecoding.cert.org/confluence/display/c/SEI+C...

Has a lot of rules of the form "Do Not ..."


Running clang with the undefined sanitizer[0] goes a lot of the way towards identifying this sort of thing. I don't see why it isn't used more often.

[0] http://blog.llvm.org/2013/04/testing-libc-with-fsanitizeunde...


What would be good is a C Haters Handbook, like the The Unix-Haters Handbook[0], a conversational/anecdotal book of sticking points and solutions, be they "don't do that", "here's a recipe/workalike", or "this is subtle -- pay attention".

[0] https://en.wikipedia.org/wiki/The_Unix-Haters_Handbook


If I recall correctly the source and destination of strcpy cannot overlap. If they do it's an undefined behaviour.


Yes, you are definitely correct, that is what the standard specifies. However, many programmers assume that if the source string points to a higher memory location than the destination string, then it is ok (i.e., they want to shift a string of X bytes to the left by some amount). And they've gotten away with it for many years, because most strcpy() functions are implemented very simply (they copy one byte at a time). The problem is when 15 year old code is run on a newer platform that has an SSE4 optimized implementation of strcpy -- then they find out what is meant by "undefined behavior".


Coding in C.


Hear hear!




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: