Pregunta

I would try to store many lists (arrays) in a Glib hash. Here is the sample code:

#include <stdio.h>
#include <stdlib.h>
#include <glib.h>

#define NR 10

typedef unsigned char carr[NR];

GHashTable* hasht;
int init = 0;


int main() {

    carr *c, *d;
    int i;

    hasht = g_hash_table_new(g_str_hash, g_str_equal);
    c = g_malloc0(sizeof *c);

    for(i=0; i<NR; i++) {
    *c[i] = 70+i;
    }

    for(i=0; i<NR; i++) {
    printf("%d\n", *c[i]);
    }

    g_hash_table_insert(hasht, "1", c);

    printf("----------------\n");
    d = g_hash_table_lookup(hasht, "1");
    for(i=0; i<NR; i++) {
    printf("%d\n", *d[i]);
    }

    return 0;
}

You can compile this code with this way:

gcc -Wall -o arrtest arrtest.c `pkg-config --cflags --libs glib-2.0`

If I run the compiled code, I got this error:

*** Error in `./arrtest': malloc(): memory corruption: 0x00000000018efe70 ***

But if I change the order of two lines above:

hasht = g_hash_table_new(g_str_hash, g_str_equal);
c = g_malloc0(sizeof *c);

to this:

c = g_malloc0(sizeof *c);
hasht = g_hash_table_new(g_str_hash, g_str_equal);

the code runs without any problems.

Why?

The project would be to store many lists as this:

a = {0, 1, 3, 4, 2, 0, 5, 9, 20};

and every list has a string key. The function should be like this:

store_in_hash(char * key, int idx)

which called from another places. The function checks if the global hash table exists, if not, creates it. Then looks up the key, if doesn't exist, creates a new one, and increments the idx'th item of list. What's the expected way to store many lists in a hash table?

Thank you for your help:

airween

¿Fue útil?

Solución

The problem here is operator precedence:

*c[i] = 70+i;

The array indexing happens before the pointer dereference. So you want (*c)[i] instead. BTW, I'd avoid this confusing code style; your typedef is not necessary, just use char pointers and you won't get into this weird situation.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top