This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

tfind


Hello,
Could someone tell me why the following program does not print anything out. I 
am using gcc 4.1.3 and libc 2.6.1 on Kubuntu 7.1

The result of the call to tfind is the same memory location pointed to 
by 'tree', however the memory location of 'a' is several bytes past that 
location.

I noted in the source code for <search.h> this comment:
/* The tsearch routines are very interesting. They make many
   assumptions about the compiler.  It assumes that the first field
   in node must be the "key" field, which points to the datum.
   Everything depends on that.  */

Which, disregarding any mistakes in my code, would explain things.

Regards,
Andrew Ward.

#include <stdlib.h>
#include <string.h>
#include <search.h>

typedef struct A_
{
    char * name;
} A;

int mycmp(const void * a1, const void * a2)
{
    return strcmp(((A *)a1)->name, ((A *)a2)->name);
}

void free_tree_item(void * i)
{}

int main()
{
    void * tree = NULL;
    char * name = "Name";

    A * a;
    a = malloc(sizeof(A));
    a->name = malloc(strlen(name) + 1);
    strcpy(a->name, name);

    tsearch(a, &tree, mycmp);

    void * found = tfind(a, &tree, mycmp);
    if(found)
    {
        puts(((A *)found)->name);
    }

    free(a->name);
    free(a);
    tdestroy(tree, free_tree_item);
}


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]