The code used to look like this:
z_User[31];
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;
z_User[LEN_USER];
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:
Post a Comment