Linux Removes Strncpy

Back when I learned C, people were still using strcpy and even gets. After a while, people started saying that strcpy wasn’t safe and that you should use strncpy instead to avoid buffer overruns, either accidental or deliberate.

Those days are long gone, of course, and now even strncpy is considered unsafe. Because of that the Linux project just completed a six year project to banish strncpy from the Linux kernel. The idea was to replace strncpy with strscpy, which fixes the problem with strncpy. The project was a lot more complicated than a simple string replace. Each instance had to be examined to see what the proper remediation was. You can read all about it in Stephen Smith’s blog.

Smith’s post has a nice chart that shows what function you should use for string copying depending on the use case. It’s useful to help you make the right choice when you need to copy a string or, more generally, a chunk of memory from one place to another.

These days there are a lot of people saying that C is unsafe and shouldn’t be used. Those of us who were brought up using it reject that and claim that in the hands of a careful coder, C is still the best language for a wide range of problems.

Even if you’re convinced that you don’t want to write your applications in C, the chances are good that at some point you’ll have to maintain or extend such an application. It is, therefore, useful to know how to do it safely. Smith’s post is a good place to learn how to deal with copying strings safely.

This entry was posted in General and tagged , . Bookmark the permalink.