Paldan
Paldan

Reputation: 435

Allocating memory to array of strings in c

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!

Upvotes: 0

Views: 149

Answers (1)

R Sahu
R Sahu

Reputation: 206567

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);

Upvotes: 3

Related Questions