Replacing strcpy with strncpy

Say I have legacy code that was written using unsafe calls to C STL functions, such as strcpy. We all know that it strcpyis unsafe because it leaves the program vulnerable to buffer overflow problems. Say I want to replace all calls strcpywith calls strncpy. The method of replacing all calls with strcpy(dest, src)will include a call strncpywith parameters (dest, src, length of dest - 1), and then ending destwith \0. I know that the problem is that we do not always know the length dest, because it may be a pointer to the memory allocated on the heap.

Suppose I can determine the length destat each of these call sites. I could replace all calls with strcpycalls strncpythat ensure that my program is immune to buffer overflow attacks (at least from misuse strcpy). However, this approach can quietly crop data and change program behavior in an undesirable way. Is this a better approach than truncation detection and program interruption? Or is it better to allow truncation, but also write it?

I ask from the point of view of who is interested in developing an automated method for fixing outdated code. Anyone have any thoughts on how best to approach this issue?

+4
source share
2 answers

We all know that it is strcpyunsafe because it leaves the program vulnerable to buffer overflow problems.

This is not a mistake strcpyin the least: programmers need to make sure that the line will fit into their buffer, for example, by calling strlenbefore copying or ensuring that the line that comes in cannot be longer than their buffer.

Say I want to replace all calls strcpywith callsstrncpy

, : , strncpy , . " " strcpy, strlcpy.

. , ? , ?

. , : , -, ; , , , . , , .

+6

strncpy STL.:) C STL. , , strcpy strncpy. . strcpy.

+1

All Articles