[OPEN-ILS-DEV] C nits: utils.c (Part 5)
Scott McKellar
mck9 at swbell.net
Tue Mar 27 00:11:11 EDT 2007
The stringisnum() function has a memory leak.
It dynamically allocates a buffer w but never frees it. After the call
to strtol() it cannot free the buffer because the pointer to it has
been overwritten.
Fortunately this function doesn't need to allocate a buffer, and
doesn't use it for anything anyway. You can drop the malloc() and
the bzero(), declare w as a bare character pointer, and let strtol()
populate it.
The attachment features three drop-in replacements for the present
stringisnum(), along with a test driver that tests each command line
parameter with stringisnum() and each of its candidate replacements.
The first is str_is_integer(), which eliminates the buffer as
described above. It also eliminates the call to strlen(), on the
grounds that you don't really care about the length of the remaining
string, you care only about whether it's empty. For that you need
only look at the first character.
The second is str_is_integer_2(). It performs exactly the same
validation as stringisnum() or str_is_integer(), by examining the
input string character by character without calling strtol(). This
approach should be faster because it doesn't bother to calculate a
value for the digit string. You don't need or use the value.
The third is str_is_long(). It tests errno after calling strtol()
in order to determine whether the number represented by the input
string can be represented as a long. I don't know if this behavior
is part of the intended requirement.
So far as I can tell from my testing, all four versions produce the
same results, except that str_is_long() returns 0 instead of 1 when
a digit string like 584746485748458574647 is too long to be a long.
Note that each of the three proposed replacements accepts a const
pointer as a pointer rather than a non-const pointer, so that you
can pass const strings to them.
Scott McKellar
http://home.swbell.net/mck9/aargh/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: testnum.c
Type: text/x-csrc
Size: 2472 bytes
Desc: 1309610990-testnum.c
Url : http://list.georgialibraries.org/pipermail/open-ils-dev/attachments/20070326/0d32e919/testnum.bin
More information about the Open-ils-dev
mailing list