I am newer to C and do some practice,in this example,i want construct a table which can contains alot of element which is Symbol type,but i don't konw how to write that part.I want to use malloc to allocate heap memory to Symbol and insert into the table(SymbolTable).
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<string.h>
typedef struct {
char *name;
uint32_t addr;
}Symbol;
typedef struct {
Symbol* tbl;
uint32_t len;
uint32_t cap;
int mode;
} SymbolTable; /*this is the table i want to mantiply*/
SymbolTable* create_table(int mode) {
SymbolTable* st = (SymbolTable*)malloc(sizeof(SymbolTable));
if (st != NULL)
{
st->mode = mode;
st->len = 0;
return st;
}
printf("Memory allocation failed!\n");
return NULL;
}
void free_table(SymbolTable* table) {
int i;
for (i = 0; i < table->len; ++i)
{
free(table->tbl[i].name);
free(&(table->tbl[i]));
}
free(table);
}
int add_to_table(SymbolTable* table, const char* name, uint32_t addr) {
if (addr % 4 != 0)
{
printf("Address alignment erron!\n");
return -1;
}
int table_len = table->len;
if (table->mode == 1)
{
int i;
for (i = 0; i < table_len; ++i)
{
if (*((table->tbl[i]).name) == *name)
{
printf("Name existed!\n");
return -1;
}
`I don't know how to inset element here`
}
}
return 0;
}
int main()
{
SymbolTable * st = create_table(0);
add_to_table(st, "aaa", 4);
add_to_table(st, "bb", 8);
write_table(st, stdout);
free_table(st);
}
There are few problems with your code as it is; also, I had to make a few assumptions since you didn't specify those details in your question:
cap is the capacity of table->tbl, i.e. how much memory we have allocated
When adding a new symbol, we should copy the string containing its name, rather than just assigning that pointer to our new Symbol entry.
You should also pick one coding style and stick to it (braces on same vs new line, T* ptr vs T *ptr etc). Finally, I've removed the cast in create_table; see Do I cast the result of malloc?
Here is a fixed version of your code; in add_to_table, if we don't have enough memory to add a new one, we double the capacity of our Symbol array (calling realloc every single time to add space for one more element would be wasteful). When we extend the capacity of our array, we must take care to set each name pointer to NULL, because if we don't and free_table is called when cap > len, we'd be trying to free an uninitialized pointer (whereas calling free on NULL is perfectly fine and does nothing).
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
typedef struct
{
char* name;
uint32_t addr;
} Symbol;
typedef struct
{
Symbol* tbl;
uint32_t len;
uint32_t cap;
int mode;
} SymbolTable; /*this is the table i want to mantiply*/
SymbolTable* create_table(int mode)
{
SymbolTable* st = malloc(sizeof(SymbolTable));
if (st != NULL)
{
st->tbl = NULL;
st->mode = mode;
st->len = 0;
st->cap = 0;
return st;
}
printf("Memory allocation failed!\n");
return NULL;
}
void free_table(SymbolTable* table)
{
int i;
for (i = 0; i < table->cap; ++i)
{
free(table->tbl[i].name);
}
free(table->tbl);
free(table);
}
int add_to_table(SymbolTable* table, const char* name, uint32_t addr)
{
if (addr % 4 != 0)
{
printf("Address alignment erron!\n");
return -1;
}
int table_len = table->len;
if (table->mode == 1)
{
int i;
for (i = 0; i < table_len; ++i)
{
if (!strcmp(table->tbl[i].name, name))
{
printf("Name existed!\n");
return -1;
}
}
if (table_len + 1 > table->cap)
{
// allocate more memory
uint32_t new_cap = table->cap ? table->cap * 2 : 2;
table->tbl = realloc(table->tbl, new_cap * sizeof(*table->tbl));
if (table->tbl == NULL)
{
// handle the error
}
table->cap = new_cap;
int i;
for (i = table_len; i < new_cap; ++i)
{
table->tbl[i].name = NULL;
}
}
uint32_t name_len = strlen(name);
table->tbl[table_len].name = malloc(name_len + 1);
strncpy(table->tbl[table_len].name, name, name_len);
table->tbl[table_len].name[name_len] = '\0';
table->tbl[table_len].addr = addr;
table->len++;
}
return 0;
}
int main(void)
{
SymbolTable* st = create_table(1);
add_to_table(st, "aaa", 4);
add_to_table(st, "bb", 8);
write_table(st, stdout);
free_table(st);
}
Firstly, I think you need to allocate *tbl and set cap (if he contain the max nb of cell in your table) in create_table().
Next, in add_to_table(), try to malloc(sizeof(struct symbol)) if (len < cap) and allocate memory for *name, and set up to your value (don't forget the \0 at the end of *name). Assign this to tbl[len] and do not forget to increment len.
Try to separate in little function, like int is_in_table(const char *name) who return the index or -1, or symbol new_symbol(const char *name, Uint32 addr) who create and set new symbol.
I hope that I have been useful for you :).
Use the concept of implementing Self-Referential structure.
Giving hints:
typedef struct S{
char *name;
uint32_t addr;
S* next;
}Symbol;
typedef struct {
Symbol* tbl;
uint32_t len;
int mode;
} SymbolTable;
http://www.how2lab.com/programming/c/link-list1.php
self referential struct definition?
Possible Implementation
#include<stdio.h>
#include<stdlib.h>
#include<stdint.h>
#include<string.h>
#include <stdio.h>
typedef struct S{
char *name;
uint32_t addr;
S* next;
}Symbol;
typedef struct {
Symbol* tbl;
uint32_t len;
int mode;
} SymbolTable; /*this is the table I want to maltiply*/
SymbolTable* create_table(int mode) {
SymbolTable* st = (SymbolTable*)malloc(sizeof(SymbolTable));
if (st != NULL)
{
st->tbl = NULL;
st->mode = mode;
st->len = 0;
return st;
}
printf("Memory allocation failed!\n");
return NULL;
}
void free_table(SymbolTable* table) {
free(table);
}
int add_to_table(SymbolTable* table, char* name, uint32_t addr) {
if (addr % 4 != 0)
{
printf("Address alignment erron!\n");
return -1;
}
int table_len = table->len;
if (table->mode == 1)
{
if (table_len == 0)
{
Symbol *t = (Symbol*)malloc(sizeof(Symbol));
t->name = name;
t->next = NULL;
table->len++;
table->tbl = t;
}
else
{
Symbol *t = table->tbl;
while (t->next != NULL)
{
if (t->name == name)
{
printf("Name existed!\n");
return -1;
}
t = t->next;
}
if (t->name == name)
{
printf("Name existed!\n");
return -1;
}
t->next = (Symbol*)malloc(sizeof(Symbol));
table->len++;
t->next->name = name;
t->next->next = NULL;
}
}
return 0;
}
void write_table(SymbolTable *st)
{
Symbol *t = st->tbl;
while (t != NULL)
{
printf("%s\n",t->name);
t = t->next;
}
printf("\n");
}
int main()
{
SymbolTable *st = create_table(0);
st->mode = 1;// Table mode setting to 1 for importing next value to table.
// You may implement it in your own way.
add_to_table(st, "cc", 8);
st->mode = 1;
add_to_table(st, "bb", 8);
st->mode = 1;
write_table(st);
free_table(st);
}
Related
I've a problem with memory allocation for an hash table with linked list (for avoid collisions) in C.
I think that the problem is on allocation of an item.
I've made two scruct, one for the single item and one for the table.
The first have two pointer to next and prev item.
Please help me.
I stay on this code until 3 days.
The code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CAPACITY 50000
unsigned long hash(char *str) {
unsigned long int stringsum = 0;
for(; *str != '\0'; str++) {
stringsum += *str;
}
return stringsum % CAPACITY;
}
typedef struct item {
char *value;
char *key;
struct item *next;
struct item *prev;
} ht_item;
typedef struct hashtable {
ht_item **items;
int dim;
int count;
} HashTable;
HashTable* create_table(int size); HashTable* create_item(HashTable *table, char *value, char *key);
void print_table(HashTable* table, int dim);
int main(void) {
HashTable *table = create_table(CAPACITY);
table = create_item(table, "Giuseppe", "Nome");
print_table(table, CAPACITY);
return 0;
}
HashTable* create_item(HashTable *table, char *value, char *key) {
unsigned long index = hash(key);
printf("%u", index);
ht_item *_iterator; ht_item *prev;
for(_iterator = table->items[index], prev = NULL; _iterator != NULL; prev = _iterator, _iterator = _iterator->next);
_iterator = (ht_item*)malloc(sizeof(ht_item));
_iterator->key = (char*)malloc(200);
_iterator->value = (char*)malloc(200);
strcpy(_iterator->key, key);
strcpy(_iterator->value, value);
_iterator->next = NULL;
_iterator->prev = prev;
return table;
}
HashTable* create_table(int size)
{
HashTable *table = (HashTable*)malloc(sizeof(HashTable));
table->dim = size;
table->items = (ht_item**)calloc(size, sizeof(ht_item*));
for(int i = 0; i < size; i++){
table->items[i] = NULL;
}
return table;
}
void print_table(HashTable* table, int dim) {
for(int i = 0; i < CAPACITY; i++)
{
if(table->items[i] != NULL)
{ ht_item *_iterator = (ht_item*)malloc(sizeof(ht_item));
for(_iterator = table->items[i]; _iterator != NULL;
_iterator = _iterator->next)
{
printf("Key: %s\tValue: %s\n", _iterator->key, _iterator->value);
} free(_iterator);
}
}
}
Made some changes in your code. Please read through the blocks containing // CHANGE HERE comment.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CAPACITY 50000
// CHANGE HERE - additional parameter, value to be used for modulo
unsigned long hash(char *str, unsigned int mod_value) {
unsigned long int stringsum = 0;
for(; *str != '\0'; str++) {
stringsum += *str;
}
// CHANGE HERE - use mod_value instead of CAPACITY
return stringsum % mod_value;
}
typedef struct item {
char *value;
char *key;
struct item *next;
struct item *prev;
} ht_item;
typedef struct hashtable {
ht_item **items;
int dim;
int count;
} HashTable;
HashTable* create_table(int size); HashTable* create_item(HashTable *table, char *value, char *key);
void print_table(HashTable* table, int dim);
int main(void) {
HashTable *table = create_table(CAPACITY);
table = create_item(table, "Giuseppe", "Nome");
print_table(table);
return 0;
}
HashTable* create_item(HashTable *table, char *value, char *key) {
// CHANGE HERE - function arguments validation
if (table == NULL)
{
return table;
}
if (value == NULL || key == NULL)
{
printf("Key or value is null\n");
return table;
}
// CHANGE HERE - pass table->dim to hash
unsigned long index = hash(key, table->dim);
printf("Index: %lu\n", index);
// CHANGE HERE - simplified the code a bit
ht_item* new_node = malloc(sizeof(ht_item));
new_node->key = malloc(200 * sizeof(char));
strncpy(new_node->key, key, 200);
new_node->value = malloc(200 * sizeof(char));
strncpy(new_node->value, value, 200);
// CHANGE HERE - if first node in index
if (table->items[index] == NULL)
{
table->items[index] = new_node;
return table;
}
ht_item *cur, *prev = NULL;
for(cur = table->items[index]; cur != NULL; prev = cur, cur = cur->next);
prev->next = new_node; // CHANGE HERE - it seems this line was missing
new_node->prev = prev;
new_node->next = NULL;
return table;
}
HashTable* create_table(int size)
{
HashTable *table = (HashTable*)malloc(sizeof(HashTable));
table->dim = size;
table->items = (ht_item**)calloc(size, sizeof(ht_item*));
for(int i = 0; i < size; i++){
table->items[i] = NULL;
}
return table;
}
void print_table(HashTable* table) {
// CHANGE HERE - function arguments validation
if (table == NULL)
{
printf("Table is null\n");
return;
}
// CHANGE HERE - change CAPACITY to dim
for(int i = 0; i < table->dim; i++)
{
//printf("i = %d [%d]\n", i, table->items[i] == NULL);
if(table->items[i] != NULL)
{
// CHANGE HERE - removed unnecessary malloc
ht_item *_iterator = NULL;
for(_iterator = table->items[i]; _iterator != NULL; _iterator = _iterator->next)
{
printf("Key: %s\tValue: %s\n", _iterator->key, _iterator->value);
}
}
}
}
The create_item function can and should be simplified.
I have put some comments inline.
HashTable* create_item(HashTable *table, char *value, char *key) {
// use modulo operator here, not in the hash function
unsigned long index = hash(key) % table->dim;
// nicer way of allocating
ht_item *insert = malloc(sizeof *insert);
// use strdup to avoid wasted memory and buffer overflows
insert->key = strdup(key);
insert->value = strdup(value);
// head insert rather than tail
insert->next = table->items[index];
table->items[index] = insert;
return table;
}
I dropped the use of the prev member. If you need that somewhere it's an exercise for you to add it. I don't think it's necessary for a simple hash table.
so basically I wrote a program to initialize, insert, and output the whole hash table. I thought I did pretty good, but there's many issues.
First issue being, some names are displayed with an additional weird character, why??
Second issue being, I can only input a size parameter (for initialize(size) function) of <8. Anything above 7 will output "Out of Space!" but why?? I thought I managed the space pretty well from what I was taught at uni:((
Please help!
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct list_node *node_ptr;
struct list_node
{
node_ptr next;
char *key;
char *value;
};
typedef node_ptr LIST;
typedef node_ptr position;
struct hash_table
{
LIST *list_ptr_arr;
unsigned int table_size;
};
typedef struct hash_table *HASHTABLE;
unsigned long long int
hash(const char *key, unsigned int hash_size)
{
unsigned long long int hash;
for(int i = 0; key[i]; i++)
{
hash = (hash<<32)+key[i];
}
return (hash%hash_size);
}
unsigned int
next_prime(int number)
{
int j;
for(int i = number; ; i++)
{
for(j = 2; j<i; j++)
{
if(i%j == 0){break;}
}
if(i==j){return j;}
}
}
HASHTABLE
initialize(unsigned int table_size)
{
HASHTABLE H;
H = (HASHTABLE) malloc(sizeof(struct hash_table));
if(H==NULL){printf("Out of Space!"); return 0;}
H->table_size = next_prime(table_size);
H->list_ptr_arr = (position*) malloc(sizeof(LIST)*H->table_size);
if(H->list_ptr_arr==NULL){printf("Out of Space!"); return 0;}
H->list_ptr_arr = (LIST*) malloc(sizeof(struct list_node)*H->table_size);
for(unsigned int i = 0; i<H->table_size; i++)
{
if(H->list_ptr_arr[i]==NULL){printf("Out of Space!"); return 0;}
H->list_ptr_arr[i]=NULL;
}
return H;
}
position
set(const char *key, const char *value)
{
position entry = (position) malloc(sizeof(struct list_node));
entry->value = (char*) malloc(strlen(value)+1);
entry->key = (char*) malloc(strlen(key)+1);
strncpy(entry->key,key,strlen(key));
strncpy(entry->value,value,strlen(value));
entry->next = NULL;
return entry;
}
void
insert(const char *key, const char *value, HASHTABLE H)
{
unsigned int slot = hash(key, H->table_size);
node_ptr entry = H->list_ptr_arr[slot];
node_ptr prev;
if(entry==NULL)
{
H->list_ptr_arr[slot] = set(key, value);
return;
}
while(entry!=NULL)
{
if(strcmp(entry->key, key)==0)
{
free(entry->value);
entry->value = malloc(strlen(value)+1);
strncpy(entry->value,value,strlen(value));
return;
}
prev = entry;
entry = prev->next;
}
prev->next = set(key, value);
}
void
dump(HASHTABLE H)
{
for(unsigned int i = 0; i<H->table_size; i++)
{
position entry = H->list_ptr_arr[i];
if(H->list_ptr_arr[i]==NULL){continue;}
printf("slot[%d]: ", i);
for(;;)
{
printf("%s|%s -> ", entry->key, entry->value);
if(entry->next == NULL)
{
printf("NULL");
break;
}
entry = entry->next;
}
printf("\n");
}
}
int main()
{
HASHTABLE H = initialize(7);
insert("name1", "David", H);
insert("name2", "Lara", H);
insert("name3", "Slavka", H);
insert("name4", "Ivo", H);
insert("name5", "Radka", H);
insert("name6", "Kvetka", H);
dump(H);
return 0;
}
Then I tried to change it up a bit:
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct list_node *node_ptr;
struct list_node
{
node_ptr next;
char *key;
char *value;
};
typedef node_ptr LIST;
typedef node_ptr position;
struct hash_table
{
LIST *list_ptr_arr;
unsigned int table_size;
};
typedef struct hash_table *HASHTABLE;
unsigned long long int
hash(const char *key, unsigned int hash_size)
{
unsigned long long int hash;
for(int i = 0; key[i]; i++)
{
hash = (hash<<32)+key[i];
}
return (hash%hash_size);
}
unsigned int
next_prime(int number)
{
int j;
for(int i = number; ; i++)
{
for(j = 2; j<i; j++)
{
if(i%j == 0){break;}
}
if(i==j){return j;}
}
}
HASHTABLE
initialize(unsigned int table_size)
{
HASHTABLE H;
H = (HASHTABLE) malloc(sizeof(struct hash_table));
if(H==NULL){printf("Out of Space!1"); return 0;}
H->table_size = next_prime(table_size);
H->list_ptr_arr = (position*) malloc(sizeof(LIST)*H->table_size);
if(H->list_ptr_arr==NULL){printf("Out of Space!2"); return 0;}
H->list_ptr_arr = (LIST*) malloc(sizeof(struct list_node)*H->table_size);
for(unsigned int i = 0; i<H->table_size; ++i)
{
if(H->list_ptr_arr[i]==NULL){printf("Out of Space!3"); return 0;}
H->list_ptr_arr[i]->value="HEAD";
H->list_ptr_arr[i]->next=NULL;
}
return H;
}
void
insert(const char *key, const char *value, HASHTABLE H)
{
unsigned int slot = hash(key, H->table_size);
LIST entry = H->list_ptr_arr[slot], newNode;
newNode = (position) malloc(sizeof(struct list_node));
if(newNode==NULL){printf("Out of Space4!"); return;}
newNode->next = entry->next;
strncpy(newNode->key,key,strlen(key));
strncpy(newNode->value,value,strlen(value));
entry->next = newNode;
}
void
dump(HASHTABLE H)
{
for(unsigned int i = 0; i<H->table_size; i++)
{
position entry = H->list_ptr_arr[i];
position p = entry->next;
if(p==NULL){continue;}
printf("slot[%d]: ", i);
for(;;)
{
printf("%s|%s -> ", p->key, p->value);
if(p->next == NULL)
{
printf("NULL");
break;
}
p = p->next;
}
printf("\n");
}
}
int main()
{
HASHTABLE H = initialize(4);
insert("name1", "David", H);
insert("name2", "Lara", H);
insert("name3", "Slavka", H);
insert("name4", "Ivo", H);
insert("name5", "Radka", H);
insert("name6", "Kvetka", H);
dump(H);
return 0;
}
Thank you!
I modified the second piece of code, it runs correctly on my computer.
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 256
// typedefing struct list_node multiple times is confusing, so I remove these typedefs
struct list_node {
struct list_node *next;
// strings need storage space in the memory,
// declaring key and value as array here can save some calls to malloc()
char key[MAX_SIZE];
char value[MAX_SIZE];
};
struct hash_table {
struct list_node **list_ptr_arr;
unsigned int table_size;
};
// it's better not to hide pointer type using typedef
typedef struct hash_table HASHTABLE;
unsigned long long int hash(const char *key, unsigned int hash_size) {
// hash is not initialized originally (the value is choosed randomly)
unsigned long long int hash = 5;
for (int i = 0; key[i]; i++) {
hash = (hash << 32) + key[i];
}
return (hash%hash_size);
}
unsigned int next_prime(int number) {
int j;
for (int i = number; ; i++) {
for (j = 2; j < i; j++) {
if (i%j == 0) { break; }
}
if (i == j) { return j; }
}
}
HASHTABLE *initialize(unsigned int table_size) {
HASHTABLE *H;
// you don't need to type cast malloc() result in C
H = malloc(sizeof(*H));
H->table_size = next_prime(table_size);
// I suppose list_ptr_arr is a pointer to an array of struct list_node * object
H->list_ptr_arr = malloc(sizeof(*(H->list_ptr_arr)) * H->table_size);
for (unsigned int i = 0; i < H->table_size; ++i) {
// malloc() for H->list_ptr_arr only allocated area for struct list_node * array, the struct list_node pointed to is not allocated yet, so malloc() here
H->list_ptr_arr[i] = malloc(sizeof(*(H->list_ptr_arr[i])));
strcpy(H->list_ptr_arr[i]->value, "HEAD");
H->list_ptr_arr[i]->next = NULL;
}
return H;
}
void insert(const char *key, const char *value, HASHTABLE *H) {
unsigned int slot = hash(key, H->table_size);
struct list_node *entry = H->list_ptr_arr[slot], *newNode;
newNode = malloc(sizeof(*newNode));
newNode->next = entry->next;
// strlen() doesn't count the '\0', just use strcpy here
strcpy(newNode->key, key);
strcpy(newNode->value, value);
entry->next = newNode;
}
void dump(HASHTABLE *H) {
for (unsigned int i = 0; i < H->table_size; i++) {
struct list_node *entry = H->list_ptr_arr[i];
struct list_node *p = entry->next;
if (p == NULL) { continue; }
printf("slot[%d]: ", i);
for (;;) {
printf("%s|%s -> ", p->key, p->value);
if (p->next == NULL) {
printf("NULL");
break;
}
p = p->next;
}
printf("\n");
}
}
int main() {
HASHTABLE *H = initialize(4);
insert("name1", "David", H);
insert("name2", "Lara", H);
insert("name3", "Slavka", H);
insert("name4", "Ivo", H);
insert("name5", "Radka", H);
insert("name6", "Kvetka", H);
dump(H);
return 0;
}
P.S. Don't forget to free the hashtable.
I made a hashtable, and it runs fine, but when i run it with valgrind,it tells me there is memory leaks when creating the hashtable and a memory leak for every user insertion, 12 bytes per insertion and 40 for creating the hashtable
here is some testable code:
#include <malloc.h>
#include <stdio.h>
#include "string.h"
#include "stdlib.h"
#define initial_size 5
typedef struct user_pos {
char nick[6];
int position_in_file;
}user_pos;
typedef struct bucket{
user_pos *info;
}bucket;
typedef struct hashtable{
int size;
int elements;
bucket **buckets;
}hashtable;
unsigned hash(char *s) {
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31*hashval;
return hashval;
}
hashtable * create() {
hashtable *htable;
if((htable = malloc(sizeof(hashtable))) == NULL)
return NULL;
if((htable->buckets = malloc(sizeof(bucket) * initial_size)) == NULL)
return NULL;
htable->size = initial_size;
htable->elements = 0;
for(int i=0; i < initial_size; i++){
htable->buckets[i] = NULL;
}
return htable;
}
void insert(hashtable *hashtable, char *nick, int position_in_file){
int hash_value = hash(nick);
int new_position = hash_value % hashtable->size;
if (new_position < 0) new_position += hashtable->size;
int position = new_position;
while (hashtable->buckets[position] != NULL && position != new_position - 1) {
if(hashtable->buckets[position]->info != NULL){
position++;
position %= hashtable->size;
}else{
break;
}
}
hashtable->buckets[position] = malloc(sizeof(bucket));
hashtable->buckets[position]->info = malloc(sizeof(user_pos));
strcpy(hashtable->buckets[position]->info->nick, nick);
hashtable->buckets[position]->info->position_in_file = position_in_file;
hashtable->elements++;
}
void delete_hashtable(hashtable *ht) {
for(int i = 0; i<ht->size; i++){
if(ht->buckets[i] != NULL && ht->buckets[i]->info != NULL)
free(ht->buckets[i]);
}
free(ht);
}
int main(){
hashtable *ht = create();
insert(ht, "nick1", 1);
insert(ht, "nick2", 2);
delete_hashtable(ht);
return 0;
}
I am initializing a bucket everytime i insert a new item, but i think i cant free it after, because that would erase what was just added, the same for the create() function.
How do i avoid leaking memory in this case?
Thanks in advance.
The memory leak is not in your allocation function but in the cleanup. You fail to free everything you allocated in delete_hashtable.
You clean up ht->buckets[i] and ht, but fail to clean up ht->buckets[i]->info and ht->buckets. You need to free those as well:
void delete_hashtable(hashtable *ht) {
for(int i = 0; i<ht->size; i++){
if(ht->buckets[i] != NULL && ht->buckets[i]->info != NULL)
free(ht->buckets[i]->info);
free(ht->buckets[i]);
}
free(ht->buckets);
free(ht);
}
Also, you're allocating the wrong number of bytes for htable->buckets:
if((htable->buckets = malloc(sizeof(bucket) * initial_size)) == NULL)
Each element is a bucket *, not a bucket, so that's the size you should use:
if((htable->buckets = malloc(sizeof(bucket *) * initial_size)) == NULL)
Or better yet:
if((htable->buckets = malloc(sizeof(*htable->buckets) * initial_size)) == NULL)
That way it doesn't matter what the type of htable->buckets is or if you change it later.
I'm trying to find out which part of my code causes memory leaks.
To be more specific I already presume where it all begins but have no idea what to do to fix it.
These are my structures:
typedef struct {
char *suffix;
int occurr;
} suff_t;
typedef struct {
char **prefix;
suff_t **suffix;
int n_suff;
int cap_suff;
} data_t;
typedef struct node {
data_t *d;
struct node *left, *right;
} node_t, *tree_t;
And functions where I use malloc / realloc :
tree_t insert( tree_t t, char **buf, int ngram ) {
if( t == NULL ) {
node_t *n = malloc( sizeof *n);
n->d = create_data(buf, ngram);
n->left = n->right = NULL;
return n;
} else if( cmp_data( t->d, buf, ngram ) > 0 ) {
t->left = insert( t->left, buf, ngram);
return t;
} else if( cmp_data( t->d, buf, ngram ) < 0 ) {
t->right = insert( t->right, buf, ngram);
return t;
} else { // add suffix
insert_suffix(t->d, buf, ngram);
return t;
}
}
void insert_suffix(data_t *data, char **buf, int ngram) {
int i;
int cap;
for(i = 0; i < data->n_suff; i++) {
if( ! (strcmp(buf[ngram-1], data->suffix[i]->suffix)) ) {
data->suffix[i]->occurr++;
return;
}
}
if(data->n_suff == data->cap_suff){ // extend table of suffixes
cap = data->cap_suff;
data->suffix = realloc(data->suffix, 2*cap*sizeof*data->suffix); //
for(i = cap; i < 2*cap; i++)
data->suffix[i] = malloc(sizeof(suff_t));
data->cap_suff *= 2;
}
data->suffix[data->n_suff]->suffix = strdup(buf[ngram-1]);
data->suffix[data->n_suff]->occurr = 1;
data->n_suff++;
}
data_t * create_data(char **buf, int ngram) {
int i;
data_t *newdata = malloc(sizeof*newdata); //
newdata->prefix = malloc((ngram-1)*sizeof*newdata->prefix);
for(i = 0; i < ngram-1; i++) // copy prefix
newdata->prefix[i] = strdup(buf[i]);
newdata->suffix = malloc(8*sizeof*newdata->suffix);
for(i = 0; i < 8; i++)
//newdata->suffix[i] = malloc(sizeof*newdata->suffix[i]);
newdata->suffix[i] = calloc(sizeof*newdata->suffix[i], 1);
newdata->suffix[0]->suffix = strdup(buf[ngram-1]);
newdata->suffix[0]->occurr = 1;
newdata->n_suff = 1;
newdata->cap_suff = 8;
return newdata;
}
void free_data(data_t *d, int ngram) {
int i;
if(d == NULL) return;
printf("deleting data\n");
for(i = 0; i < ngram-1; i++)
free(d->prefix[i]);
free(d->prefix);
for(i = 0; i < d->cap_suff; i++) {
free(d->suffix[i]->suffix);
free(d->suffix[i]);
}
free(d->suffix);
free(d);
}
void free_tree(tree_t t, int ngram) {
if( t == NULL) return;
free_data(t->d, ngram);
free(t->left);
free(t->right);
printf("DELETING NODE\n");
free(t);
}
Valgrind prompts that something is wrong with function create_data and insert .
Please help
Valgrind is pointing to the place where the memory was allocated, not where you failed to release it.
The cuplrit is almost certainly free_tree. A tree is a recursive data-structure, which means you need to free it recursively. You are only freeing the root node.
Change these lines:
free(t->left);
free(t->right);
to
free_tree(t->left);
free_tree(t->right);
though I'm not sure what you'd provide as ngram. Probably pass in the original.
The point is that you have to navigate down each branch, freeing from the bottom up before releasing the node itself.
I'm looking for some help with some C dll programming. I am getting an error in Visual Studio that occurs when I call free from within the dll. The program runs fine in debug mode within the IDE, but when I try to execute it as "Start without debugging", the program crashes. I read that with debugging, the heap is shared, which probably explains why the code runs fine with F5 and not Ctrl-F5. Is this correct??
I've searched around, and I learned that it is dangerous to pass dynamically allocated memory through the dll-exe boundary, however as I am calling malloc and free from within the same dll, this should not be a problem. I have posted the code below. Any help would be greatly appreciated. Please note that this code works on my Linux box, I am simply trying to port it to Windows to garner experience programming in Windows.
Thank you
#ifndef HASHTABLE_H
#define HASHTABLE_H
// The following ifdef block is the standard way of creating macros which make exporting
// from a DLL simpler. All files within this DLL are compiled with the HASHTABLE_EXPORTS
// symbol defined on the command line. This symbol should not be defined on any project
// that uses this DLL. This way any other project whose source files include this file see
// HASHTABLE_API functions as being imported from a DLL, whereas this DLL sees symbols
// defined with this macro as being exported.
#ifdef HASHTABLE_EXPORTS
#define HASHTABLE_API __declspec(dllexport)
#else
#define HASHTABLE_API __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
/**
* This is a naive implementation
* of a hashtable
*/
typedef struct node {
struct node *next;
char *value;
char *key;
} Node;
typedef struct hashtable {
struct node **nodes;
int num_elements;
int size;
int (*hash_function)(const char * const);
} Hashtable_str;
// Construction and destruction
HASHTABLE_API void tbl_construct(Hashtable_str **table);
HASHTABLE_API void tbl_destruct(Hashtable_str *table);
// Operations
HASHTABLE_API int tbl_insert (Hashtable_str *table, const char * const key, const char * const element); // return the key
HASHTABLE_API int tbl_remove(Hashtable_str *table, const char * const key);
HASHTABLE_API char * tbl_find(Hashtable_str *table, const char * const key); // return the element
HASHTABLE_API int size(Hashtable_str *table); // Return the size
// default hash function
int def_hash(const char * const key);
#ifdef __cplusplus
}
#endif
#endif
Here is the implementation code
// hashtable.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "hashtable.h"
#include <stdlib.h> // for memcpy
#include <stdio.h>
#include <string.h>
#define SIZE 100
int def_hash(const char * const key)
{
// simply sum the ascii
// values and take modulo
// 100
//int i;
//int sum;
//sum = 0;
//for (i=0; key[i] != '\0'; i++)
// sum += key[i];
//return sum % SIZE;
return 0;
}
// construct a hashtable and return a pointer
HASHTABLE_API void tbl_construct(Hashtable_str **tbl)
{
int i;
Hashtable_str *tbl_ptr;
*tbl = (Hashtable_str*) malloc (sizeof(Hashtable_str*));
tbl_ptr = *tbl;
tbl_ptr->nodes = (Node**) malloc (SIZE * sizeof(Node*));
for (i=0; i < SIZE; i++) tbl_ptr->nodes[i] = NULL;
tbl_ptr->hash_function = &def_hash;
tbl_ptr->num_elements = 0;
tbl_ptr->size = SIZE;
}
HASHTABLE_API void tbl_destruct(Hashtable_str *tbl)
{
void free_tbl_node(Node*); // declare the release function
int i;
for (i=0; i < tbl->size; i++)
{
if (tbl->nodes[i] != NULL)
free_tbl_node(tbl->nodes[i]);
}
}
void free_tbl_node(Node *curr_node)
{
if (curr_node->next != NULL)
free_tbl_node(curr_node->next);
free(curr_node->value);
curr_node->value = NULL;
free(curr_node->key);
curr_node->key = NULL;
//free(curr_node);
//Node *temp = NULL;
//Node *temp2 = NULL;
//temp = temp2 = curr_node;
//while (temp->next != NULL)
//{
// temp2=temp->next;
// free(temp->key);
// free(temp->value);
// free(temp);
// temp=temp2;
//}
}
// table operations
HASHTABLE_API int count(Hashtable_str *tbl) { return tbl->num_elements; }
HASHTABLE_API int size(Hashtable_str *tbl) { return tbl->size; }
HASHTABLE_API int tbl_insert(Hashtable_str *table, const char * const key, const char * const element)
{
int hash;
Node *temp_ptr = NULL;
hash = table->hash_function(key);
// printf("Placing into column %d\n", hash);
if (table->nodes[hash] == NULL)
{
table->nodes[hash] = (Node*) malloc(sizeof(Node*));
temp_ptr = table->nodes[hash];
temp_ptr->next = NULL;
temp_ptr->key = (char*) malloc (strlen(key) + 1 * sizeof(char));
temp_ptr->value = (char*) malloc (strlen(element) + 1 * sizeof(char));
strcpy_s(temp_ptr->key, strlen(key)+1, key);
strcpy_s(temp_ptr->value, strlen(element)+1, element);
table->num_elements += 1;
}
else
{
// Collision!!
temp_ptr = table->nodes[hash];
while (temp_ptr->next != NULL)
temp_ptr = temp_ptr->next;
temp_ptr->next = (Node*) malloc(sizeof(Node));
temp_ptr->next->key = (char*) malloc (strlen(key)+1 * sizeof(char));
temp_ptr->next->value = (char*) malloc (strlen(element)+1 * sizeof(char));
temp_ptr->next->next = NULL;
strcpy_s(temp_ptr->next->key, strlen(key)+1, key);
strcpy_s(temp_ptr->next->value, strlen(element)+1, element);
table->num_elements += 1;
}
// Return the hash value itself for hacking
return hash;
}
HASHTABLE_API int tbl_remove(Hashtable_str *tbl, const char * const key)
{
int hash;
Node *temp_ptr = NULL;
Node *chain = NULL;
hash = tbl->hash_function(key);
if (tbl->nodes[hash] == NULL)
return 1;
else
{
temp_ptr = tbl->nodes[hash];
if (strcmp(key, temp_ptr->key) == 0)
{
// The next node is the node in question
chain = temp_ptr->next;
free(temp_ptr->value);
printf("Deleted the value\n");
free(temp_ptr->key);
printf("Deleted the key\n");
//printf("About to delete the node itself\n");
//free(temp_ptr);
tbl->nodes[hash] = chain;
tbl->num_elements -= 1;
return 0;
}
else
{
while (temp_ptr->next != NULL)
{
if (strcmp(key, temp_ptr->next->key) == 0)
{
// The next node is the node in question
// So grab a pointer to the node after it
// and remove the next node
chain = temp_ptr->next->next;
free(temp_ptr->next->key);
free(temp_ptr->next->value);
//free(temp_ptr->next);
temp_ptr->next = chain;
tbl->num_elements -= 1;
return 0;
}
else
temp_ptr = temp_ptr->next;
}
}
// Couldn't find the node, so declare not existent
return 1;
}
}
HASHTABLE_API char * tbl_find(Hashtable_str *tbl, const char * const key)
{
// Compute the hash for the index
int hash;
Node *temp_ptr = NULL;
hash = tbl->hash_function(key);
if (tbl->nodes[hash] == NULL)
return NULL;
else
{
temp_ptr = tbl->nodes[hash];
if (strcmp(key, temp_ptr->key) != 0)
{
while (temp_ptr->next != NULL)
{
temp_ptr = temp_ptr->next;
if (strcmp(key, temp_ptr->key) == 0)
return temp_ptr->value;
}
}
// Couldn't find the node, so declare not existent
return NULL;
}
}
Here's my main
#include <hashtable.h>
#include <utils.h>
#include <stdio.h>
int main(int argc, char **argv)
{
int i=0;
Hashtable_str *my_table = NULL;
tbl_construct(&my_table);
tbl_insert(my_table, "Daniel", "Student");
tbl_insert(my_table, "Derek", "Lecturer");
//tbl_insert(my_table, "Melvyn", "Lecturer");
tbl_print(my_table);
printf("\nRemoving Daniel...\n");
tbl_remove(my_table, "Daniel");
//tbl_print(my_table);
tbl_destruct(my_table);
my_table = NULL;
scanf_s("%d", &i);
return 0;
}
This is incorrect as allocates the size of a pointer, not a Hashtable_str:
*tbl = (Hashtable_str*) malloc (sizeof(Hashtable_str*));
it should be:
*tbl = malloc(sizeof(Hashtable_str));
Same issue with:
table->nodes[hash] = (Node*) malloc(sizeof(Node*));
See Do I cast the result of malloc?