Red Hat Bugzilla – Bug 103061
hsearch_r needs better example code
Last modified: 2007-04-18 12:57:08 EDT
From Bugzilla Helper:
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.2.1) Gecko/20030225
Description of problem:
I'm converting a perl program to C, and wanted to use some hash tables. I found
the hcreate_r, hsearch_r, hdestroy_r functions in the man pages.
There is an example on how to use the old (non-reentrant) versions of these
functions, but when I tried to upgrade it to use the reentrant functions the
test program died a horrible death, mysteriously.
After much debugging, I found the problem and the solution.
Version-Release number of selected component (if applicable):
Steps to Reproduce:
1. Cut-n-paste the example from the man page
2. Define a 'struct hsearch_data foo;' in main()
3. Convert the old functions to the new functions.
4. Compile and run.
Actual Results: Crash with 'Segmentation fault' or 'Floating point error'.
Expected Results: Should have run without an error.
It turns out that the example program doesn't check the return value of the
hcreate call. If it fails to create the hash table, a divide-by-zero error will
occur in the hsearch function.
The other problem is that I didn't zero out the hsearch_data before calling
hcreate_r, which causes hcreate_r to assume that a table was already created and
so it refuses to clobber an existing hash table.
I'm including an example for the new functions.
Created attachment 93928 [details]
example program for inclusion in the man page
This code shows a working example for hcreate_r/hsearch_r. It is almost
identical to the hcreate/hsearch example, except that it clears a data
structure before use, and it checks to see if the hash table was created.
h_search and Co. is not in the latest man-pages package