0

I'm in the process of creating a hash table. I'm using a struct for the capacity, number of keys, frequencies and the keys themselves. Here is my code for initializing the struct:

htable htable_new(int capacity) {

  htable result = emalloc(sizeof *result);
  result->capacity = capacity;
  result->frequencies = emalloc(capacity * sizeof result->frequencies[0]);
  result->keys = emalloc(capacity * sizeof result->keys[0]);
  result->frequencies = 0;
  result->keys = NULL;

  return result;
}

Now, from my understanding, a char** array is a pointer to an array of pointers (of type char)? So when I allocate memory, would it be correct to use keys[0]? I assume that this just represents the size of the char pointer? Which leads to my next question of when I actually set the keys in the array (which is obviously in another function) would I just allocate memory to each index by the size of the string I input before storing it?

i.e. h->keys[index] = emalloc(sizeof(str)

Thanks for your answers!

1 Answer 1

3

Assuming emalloc is a valid macro or function,

The calls

result->frequencies = emalloc(capacity * sizeof result->frequencies[0]);
result->keys = emalloc(capacity * sizeof result->keys[0]);

are OK. However, the next two lines:

result->frequencies = 0;
result->keys = NULL;

immediately cause memory leaks. I don't know why you have them. They should be removed.

Assuming str is of type char* or char const*, the line

h->keys[index] = emalloc(sizeof(str));

won't allocate the necessary amount of memory for h->key[index]. That will allocate enough memory to hold only a char*. You need:

h->keys[index] = emalloc(strlen(str)+1);
strcpy(h->keys[index], str);
Sign up to request clarification or add additional context in comments.

2 Comments

Hey thanks for your reply I used: result->frequencies = 0; and result->keys = NULL; because I wanted to set all elements equal to 0 and NULL respectively. How do I go about that?
You can use calloc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.