Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

malloc with a multidimensional array

I'm working on a dictionary whose structure is:

typedef union _dict {
    union _dict * children[M];
    list * words[M];
} dict;

Initialisation:

dict *d = (dict*) malloc(sizeof(dict));

I'm trying to do the following:

dict *temp;
temp = d;

temp=temp->children[0];
temp=temp->children[0];

The first temp->children[0] works but not the second. I'm trying to understand why. I think it's a memory allocation problem.

Edit 1: I've tried the following code :

dict *d = (dict*) malloc(sizeof(dict));

dict *temp;
temp = d;

dict *d2 = (dict*) malloc(sizeof(dict));
temp->children[0] = d2;

temp = temp->children[0];
temp = temp->children[0];
temp = temp->children[0];

That now works, but I don't understand why... I mean, i don't have allowed some memory for next children.

Edit 2: So now, I would like to use this in my algorithm. The code block where I am stuck is the following:

list *l;
if (temp->words[occur] != NULL) {
    /* ... */
}
else {
    l = list_new();
    temp->words[occur] = (list*) malloc(sizeof(list));
    temp->words[occur] = l;
}
list_append(l,w);
list_print(l);

If I put a temp->words[occur] = NULL; before this block, the word is successfully added, but a new list is created each time the algorith is used. I would like to add my word to the previously created list, assuming it exists.

A bzero((void*)d, sizeof(dict)); instruction is used after the dict initialisation.

like image 603
kh4r4 Avatar asked Aug 19 '26 12:08

kh4r4


2 Answers

At first in temp you have a valid pointer to an object (allocated with malloc). Then you assign an uninitialized pointer to temp and attempt to dereference it with the expected consequences.

like image 115
chill Avatar answered Aug 22 '26 07:08

chill


children is never initialised, so it contains whatever garbage was in memory before. After the first temp = temp->children[0], temp is a pointer to unknown territory.

like image 44
Daniel Fischer Avatar answered Aug 22 '26 08:08

Daniel Fischer