Reputation: 435
I'm initializing a struct which represents a hash table. I'm attempting to make the frequencies = 0 and the keys = null, but I'm getting a seg fault and not too sure why. Here is my code:
htable htable_new(int capacity) {
int i;
htable result = emalloc(sizeof *result);
result->capacity = capacity;
result->frequencies = emalloc(capacity * sizeof result->frequencies[0]);
result->keys = emalloc(capacity * sizeof result->keys[0]);
for (i = 0; i < capacity; i++) {
result->frequencies[i] = 0;
}
for (i = 0; i < capacity; i++) {
result->keys[i] = NULL;
}
return result;
}
and here is the struct which I'm initializing:
struct htablerec {
int capacity;
int num_keys;
int *frequencies;
char **keys;
};
I don't see what's wrong as I'm trying to initialize all the int's i've allocated to 0, and all the char pointers to NULL. Is this wrong? Should I be doing this some other way? Thanks for your help!
Upvotes: 0
Views: 320
Reputation: 3768
Try the following (notice pointers near result and return type):
htable *htable_new(int capacity) {
int i;
htable *result = emalloc(sizeof *result);
result->capacity = capacity;
result->frequencies = emalloc(capacity * sizeof result->frequencies[0]);
result->keys = emalloc(capacity * sizeof result->keys[0]);
for (i = 0; i < capacity; i++) {
result->frequencies[i] = 0;
}
for (i = 0; i < capacity; i++) {
result->keys[i] = NULL;
}
return *result;
}
Or, as far as your structure is small, you may want to return it by value:
htable htable_new(int capacity) {
int i;
htable result = { 0 };
result.capacity = capacity;
result.frequencies = emalloc(capacity * sizeof result->frequencies[0]);
result.keys = emalloc(capacity * sizeof result->keys[0]);
for (i = 0; i < capacity; i++) {
result.frequencies[i] = 0;
}
for (i = 0; i < capacity; i++) {
result.keys[i] = NULL;
}
return result;
}
I changed result
to be an actual struct, rather than pointer to it. Because of that, it's allocated on stack, fields are initialized as usual and then I return it as is. That means, all struct will be copied to the new place.
Remember that only field of htable
are copied; capacity
and keys
are copied as pointers. That means that if you do htable a = new_htable(10); htable b = a;
then a.keys == b.keys
(they point to the same array).
I don't know, how your code compiled at all. By the way, you forgot to initialize num_keys
field and the name of struct you defined doesn't match the name of return type.
Upvotes: 1