Search code examples
cmalloccalloc

Malloc or calloc


here is a very small structure used for indexing words of a file. Its members are a string (the word), an array of integers (the lines this word is found at), and an integer representing the index of the first free cell in the lines array.

typedef struct {
    wchar_t * word;
    int * lines;
    int nLine;
} ndex;

ndex * words;

I am trying to allocate (ndex)es nb_words = 128 at a time, and (lines) nb_lines = 8 at a time, using malloc and realloc.

First question, what is the difference between malloc(number * size) and calloc(number, size) when allocating *words and/or *lines? Which should I choose?

Second question, I gdbed this:

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400cb0 in add_line (x=43, line=3) at cx17.3.c:124
124     words[x].lines[words[x].nLine] = line;
(gdb) p words[43].nLine 
$30 = 0

In other words, it consistently fails at

words[43].lines[0] = 3;

Since I allocate words by 128, and lines by 8, there is no reason the indexing worked for the 42 previous words and fail here, except if my allocating was botched, is there?

Third question: here are my allocations, what is wrong with them?

words = malloc(sizeof(ndex *) * nb_words);
short i;
for (i = 0; i < nb_words; i++) {
    words[i].lines = malloc(sizeof(int) * nb_lines);
    words[i].nLine = 0;
}

Should I initialize lines in a for(j) loop? I don't see why leaving it uninitialized would prevent writing to it, so long as it as been allocated.

This C is a very mysterious thing to me, thanks in advance for any hints you can provide.

Best regards.


Solution

  • This looks suspicious:

    sizeof(ndex *)
    

    You probably don't want the size of a pointer - you want the size of a structure. So remove the star.