Peeter Joot's (OLD) Blog.

Math, physics, perl, and programming obscurity.

Have to love perl for quicky automated source changes.

Posted by peeterjoot on July 16, 2010

Looking at some code today of the following form:

   char buf[10] ;
   sprintf( buf, "%s ... ", somefunction() ) ;

Where somefunction returns a char *. Very unsafe code since you could easily overflow buf and have all sorts of fun stack corruptions to deal with. This was repeated about 400 times in the modules in question, and it’s desirable to replace these all with snprintf calls to ensure there is no bounds error (in DB2 we use a different version of snprintf due to some portability issues, but the idea here is the same).

Here’s a nice little one liner to make the code changes required:

perl -p -i -e 's/\bsprintf *\( *(.*?), */snprintf( $1, sizeof($1), /' LIST_OF_FILENAMES

It’s not perfect, but does the job nicely in the bulk of the call sites, adding as desired, the additional sizeof() parameter to the call and changing the function name. Of course thorough review is required with context, since you don’t want to be taking sizeof() of a char * argument and get the size of a pointer.

Leave a comment