1

I am using uthash (http://uthash.sourceforge.net/userguide.html) to use a Hash Table implementation in my C Program.

I am trying to printf the data that is being added to the hash table before and after the addition and I get garbage values when I print it after the malloc. Please see the following code.

void add_user(int user_id, char *name)
{
    printf("User ID : %d Name : %s, user_id,name); // Prints fine !!
    struct my_struct *s;
    s = malloc(sizeof(struct my_struct));
    s->id = user_id;
    strcpy(s->name, name);

    printf("User ID : %d Name : %s, s->user_id,s->name); // Prints User ID fine, but for Name, only half of it is printed right, rest is Garbage !!

    HASH_ADD_INT( users, id, s );
}

If I do the following :

void add_user(int user_id, char *name)
{
    printf("User ID : %d Name : %s, user_id,name); // Prints fine !!

    struct my_struct *s;
    s = malloc(sizeof(struct my_struct));

    printf("User ID : %d Name : %s, user_id,name); // Printing same as previous printf then I get Garbage values printed for Name

}

BUT if I comment out malloc as well, then both printf statements print correctly.

HELP !!!

4

2 に答える 2

2

When r.name is a pointer, then you have to manually allocate memory for it, strcpy doesn't care for this. When it is a char array, then the memory is already there. Additionally, if the pointer wasn't initialized, then it may point to any (invalid) memory address. strcpy doesn't care for this, either, so you'd try to copy the string to this address, whereever it is.

The same may apply for your struct, as YePhIcK commented. When s.name is a pointer, then you need to allocate the memory for it:

s = malloc(sizeof(struct my_struct));
s->id = user_id;
s->name = malloc(strlen(name) + 1);
strcpy(s->name, name);

If you allocate a fixed amount or if it is a char array, then do not use strcpy for this, because it doesn't care for the destination size, too. You will end with a potential buffer overflow when the given name is longer than the available space. This is a whole discussion of its own, just search for strcpy here.

Last, malloc may fail and returns NULL then. You should always check for this and take appropriate action. This is another discussion of its own.

于 2012-07-15T09:55:51.457 に答える
1

Gosh, I posted the question and in the next 2 mins I figured it out.

YePHlcK, you are kinda right. However, the thing which didn't have the memory allocated here was *name which was coming in.

The function was called like this :

add_user(r.user_id, r.name); // r itself is a struct where name was a pointer and not a char array.

Changing name to a char array and then initializing it by using strcpy(r.name,"blah"); and then calling add solved the problem. Because strcpy would take care of allocation of memory ?!?!! Correct me if I am wrong.

Thanks!

于 2012-07-15T07:27:34.470 に答える