Why does this malloc not work in C?

You need to change sizeof(HashTable*) to sizeof(HashTable) and similarly sizeof(Entry **) to sizeof(Entry *) And the second thing is for every Entry you need to allocate memory using malloc again inside the loop.

You need to change sizeof(HashTable*) to sizeof(HashTable) and similarly sizeof(Entry **) to sizeof(Entry *) . And the second thing is for every Entry you need to allocate memory using malloc again inside the loop.

Thanks! Hmm, making this change to p for sizeof(HashTable) is giving an error allocating memory to p. Using VS 2010.

Will try it again but that seems to be what its saying. – Igor K Oct 26 '10 at 11:30 1 I would prefer sizeof(*p) to sizeof(HashTable). Then the line reads, "allocate the right thing for p", instead of "allocate this thing, which I think is the right thing for p but who knows, I might have made a mistake" :-) – Steve Jessop Oct 26 '10 at 11:40.

If ((p = malloc(sizeof(HashTable))) == NULL) return NULL; p->size = 101; if ((b = malloc(p->size * sizeof(Entry *))) == NULL) return NULL; I believe removing the malloc() result casts is best practice. Plus, as @Naveen was first to point out you also need to allocate memory for each Entry.

Firstly your sizeofs are wrong. T * = malloc( num * sizeof(T)) is correct. You can also use calloc.

You are reusing be for different purposes so it is quite confusing. Not generally good using a single character variable. P->table which was be is allocated but not initialised, i.e.It doesn't point to anything useful, then you are trying to dereference it.

You need to fill it will Entry* pointers first, and they must be pointing to valid Entry structs if you are going to dereference those. Your process probably dies on the line b>theData = NULL.

Also, you can statically declare your HashTable, either locally, or in some region high enough in the stack that the stack is non-ascending (in memory) while it is used and pass a pointer to the HashTable to your initialize function to avoid a malloc. Malloc is slow. So in main, you can do: HashTable table; InitializeHashTable(&table); // use table (no need to free) // just do not return table.

I will later have to resize the table. The idea was to create a new one, then I can just use the pointer to the new table. Not sure if I can do this if I code it this way?

Thanks for the input though, I'm not sure to be honest. – Igor K Oct 26 '10 at 12:01.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions