Re: [patch] tsearch.3: dispose properly of allocated resources in example code

Michael Kerrisk
2008-09-23T06:28:31Z

André,

On Sun, Sep 21, 2008 at 8:10 AM, André Goddard Rosa
<andre.goddard-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:
> As there are many users who base their own code on these examples, we
> should avoid leaking memory when using functions of tsearch() family.
> In the provided example, tsearch() leaks memory whenever it tries to
> insert a number which was already inserted before.

Thanks. My first patch applied via 'git am'!

I applied this patch for man-pages-3.10. (I added
#define _GNU_SOURCE
since that's required to expose the tdestroy() declaration.)

Cheers,

Michael

> --- man3/tsearch.3 2008-09-10 10:16:13.000000000 -0300
> +++ man3/tsearch.3.goddard 2008-09-21 02:42:55.000000000 -0300
> @@ -246,8 +246,11 @@
> val = tsearch((void *) ptr, &root, compare);
> if (val == NULL)
> exit(EXIT_FAILURE);
> + else if (!((*(int **) val) == ptr))
> + free(ptr);
> }
> twalk(root, action);
> + tdestroy(root, free);
> exit(EXIT_SUCCESS);
> }
> .fi
>
>

--
Michael Kerrisk
Linux man-pages maintainer; http://www.kernel.org/doc/man-pages/
man-pages online: http://www.kernel.org/doc/man-pages/online_pages.html
Found a bug? http://www.kernel.org/doc/man-pages/reporting_bugs.html