{C++ etc.}

Latest Posts
Home | C++ Posts | Linux Posts | Programming Posts | Issue Tracking Posts

Sunday, October 11, 2009

Functions that take length of strings as parameters

Lately, I've been working on a component which had HUGE issue with string lengths. The problem was that all the strings were initialized with an integer instead of defined lengths. When these were used in various places in the source, the programmer has used various lengths to alter the same string. And now I find myself faced with the nightmare of cleaning up the mess.

The code used to look like this:
pCursor->Define(3, z_User, 30); // wrong. would only copy 29 chars off a database column
pMsg->Get(5, z_User, 30); // wrong. would only copy 29 chars off a message
ToUpperCase(z_User, 30); // correct. expects user to pass the length to convert and then appends '\0'

The problem is, functions which take string length as an argument would treat this length differently. For example, strcpy requires you to give one less than the actual length of the string in order to have space to print the NULL termination character. Another problem is the situation one would find ones self in if the size of the string were to be changed (e.g. change the size of User to 50).
When writing a function which uses char buffs, it would always be prudent to implement it in a safe way so that users would not have to worry about the actual implementation and wonder how it would behave if you pass the full length of the string to it. The above code would ideally be written as (keeping the same structure):

const int LEN_USER = 51;
pCursor->Define(3, z_User, LEN_USER);
pMsg->Get(5, z_User, LEN_USER);
ToUpperCase(z_User, LEN_USER); // Function changed to accept the full length of the string

The real fun begins when you have to do these changes in multiple code paths. :)

No comments: