Segmentation fault in parsing into linked list - c

I have this program that parses and RSS feed into a linked list.
#include"util.h"
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<string.h>
void parse_tc(){
struct node *head = NULL;
char *bytes = 0;
struct stat st;
stat("techcrunch.txt", &st);
int size = st.st_size;
FILE *f = fopen("techcrunch.txt", "rb");
bytes = (char*)malloc(size + 1);
size_t nread = fread(bytes,1,size,f);
bytes[nread] = 0;
fclose(f);
struct node *temp = (struct node*)malloc(sizeof(struct node));
temp->position = 1;
printf("%d. ", temp->position);
char *a = title_parser_tc(bytes,temp);
head = temp;
for(int i = 2; i<21; i++){
temp = (struct node*)malloc(sizeof(struct node));
temp->position = i;
printf("%d. ", temp->position);
a = title_parser_tc(a, temp);
struct node* temp1 = head;
while(temp1->link != NULL)
{
temp1 = temp1->link;
}
temp1->link = temp;
}
free(bytes);
int holder = 0;
int check = 0;
do {
printf("Enter a number: ");
scanf("%d", &holder);
if(holder<1 || holder > 20){
puts("Invalid input");
check = 1;
}
else{
check = 0;
}
} while(check);
get_feed(holder, head);
}
char* title_parser_tc(char *bytes, struct node *temp){
char *ptr = strstr(bytes, "<title>");
if (ptr) {
ptr += 7;
char *ptr2 = strstr(ptr, "</title>");
if (ptr2) {
char* output = malloc(ptr2 - ptr + 1);
memcpy(output, ptr, ptr2 - ptr);
output[ptr2 - ptr] = 0;
if(strcmp(output,"TechCrunch")!=0){
temp->title = output;
puts(temp->title);
temp->link = NULL;free(output);
char *load = pubdate_parser_tc(ptr2, temp);
return load;
}
else{
char *load = title_parser_tc(ptr2, temp);
free(output);
return load;
}
}
}
return NULL;
}
char* pubdate_parser_tc(char *bytes, struct node *temp){
char *ptr = strstr(bytes, "<pubDate>");
if (ptr) {
ptr += 9;
char *ptr2 = strstr(ptr, "</pubDate>");
if (ptr2) {
char* output = malloc(ptr2 - ptr + 1);
memcpy(output, ptr, ptr2 - ptr);
output[ptr2 - ptr] = 0;
temp->pubdate = output;
free(output);
char *load = description_parser_tc(ptr2, temp);
return load;
}
}
return NULL;
}
char* description_parser_tc(char *bytes, struct node *temp){
char *ptr = strstr(bytes, "<description>");
if (ptr) {
ptr += 13;
char *ptr2 = strstr(ptr, "</description>");
if (ptr2){
char* output = malloc(ptr2 - ptr + 1);
memcpy(output, ptr, ptr2 - ptr);
output[ptr2 - ptr] = 0;
description_cleaner_tc(output, temp);
free(output);
char *load = url_parser_tc(ptr2, temp);
return load;
}
}
return NULL;
}
void description_cleaner_tc(char *bytes, struct node *temp){
char *ptr = strstr(bytes, "&nbsp;");
if (ptr) {
ptr += 10;
char *ptr2 = strstr(ptr, "<a ");
if (ptr2) {
char* output = malloc(ptr2 - ptr + 1);
memcpy(output, ptr, ptr2 - ptr);
output[ptr2 - ptr] = 0;
temp->description = output;
puts(temp->description);
free(output);
}
}
}
char* url_parser_tc(char *bytes, struct node *temp){
char *ptr = strstr(bytes, "href");
if (ptr) {
ptr += 6;
char *ptr2 = strstr(ptr, ">");
if (ptr2) {
char* output = (char*)malloc(ptr2 - ptr);
memcpy(output, ptr, ptr2 - ptr - 1);
output[ptr2 - ptr - 1] = 0;
temp->url = output;
puts(temp->pubdate);
puts(temp->url);
puts("");
free(output);
return ptr2;
}
}
return NULL;
}
My problem is that for this file textcrunch.txt, my program occurs a segmentation fault at around the 10th loop in parse_tc(). The program works for another file but this file gives me an error. Any solution?
The code is basically the same function repeated for different strings to be parsed.

Segmentation fault usually means dereferencing a null-pointer (or a pointer to uninitialized memory). If you are using GCC or Clang, you can recompile with the -g flag and run the resulting program through gdb:
gdb --args ....
r
bt
The first line starts gdb, supply your command as you would usually run it. r starts the run and bt gives a backtrace from the point your program stops with the segmentation fault. At least this gives you the location in the code the problem occurs. You could start futher debugging with print statements or add some defensive coding there.

Related

Allocate a big-chunk of memory and manage it afterwards

So, I'm currently going thorugh the book "Crafting Interpreters", one of the challenges is to allocate a big chunk of memory (only once) in the beginning of the program and manage it.
So far i've written this piece of code, but I'm not quite shure that I'm in the right direction.
#include <stdio.h>
#include "stdbool.h"
#include "stdlib.h"
typedef struct node {
_Bool free;
struct node* next;
} freeList;
#define IS_VALID(head) ((head)->next == NULL) ? 0 : 1
#define BLOCK_SIZE 8
void initFreeList(freeList* head, size_t size);
void* malloc_(freeList* head, size_t size);
void free_(freeList* head, void* var);
void initFreeList(freeList* head, size_t size)
{
freeList* ptr = NULL;
head->next = NULL;
head->free = true;
ptr = head;
for (int i = 0; i < size; i++) {
freeList* temp = malloc(sizeof(freeList*));
temp->next = NULL;
temp->free = true;
ptr->next = temp;
ptr = temp;
}
}
// Removes a node from the freeList and returns a void pointer.
void* malloc_(freeList* head, size_t size)
{
void* block = NULL;
freeList* ptr = NULL, *prev = NULL, *temp_ptr = NULL;
int counter = 0;
if (!IS_VALID(head))
return NULL;
while((size) % BLOCK_SIZE != 0)
size++;
for (ptr = head; ptr->next != NULL && ptr->free == true && counter < size;) {
counter += BLOCK_SIZE;
prev = ptr;
ptr = ptr->next;
ptr->free = false;
}
temp_ptr = ptr;
for (counter = 0; counter < size; counter += BLOCK_SIZE, temp_ptr = temp_ptr->next)
temp_ptr->free = false;
prev->next = temp_ptr->next;
temp_ptr->next = NULL;
block = ptr;
return block;
}
void free_(freeList* head, void* var)
{
_Bool flag = true;
while(head && flag) {
if (head->next == NULL) {
head->next = (freeList *) var;
head->next->free = true;
head->next->next = NULL;
flag = false;
}
head = head->next;
}
}
int main()
{
freeList* head = malloc(sizeof(freeList));
initFreeList(head, 10);
char* str = malloc_(head, 16);
int *var1 = malloc_(head, 8), *var2 = malloc_(head, 8);
sprintf(str, "%s", "Hello world !");
*var1 = 2000000000;
*var2 = 257;
free_(head, var1);
free_(head, str);
free_(head, var2);
printf("%s\n%d %d\n", str, *var1, *var2);
return 0;
}
I'm able to allocate memory for the variables in main, and when freeing the chunks are added back to the free list but some of them get lost, I guess it's because when I assigned memory using the
malloc_ im overwriting memory. What will be the right approach for this kind of problem ?

hashedmap and pointer to structs: CXX0030: Error: expression cannot be evaluated

Im trying to create a simple hashmap in C. The vs doesnt know any errors at compilation time. But during execution, the pointer to the structure is becoming a bad pointer.
hashedKey CXX0030: Error: expression cannot be evaluated
Here is the code for that, can anyone tell me why the code is crashing.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
//#include"Header.h"
struct hashItem{
char* hashedKey;
char* hashedValue;
hashItem* next;
};
#define SIZE 20
unsigned long hashf(char *str)
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return hash%SIZE;
}
struct hashItem * createNewItem(char *key, char *value){
struct hashItem *newKeyValue = (struct hashItem *)calloc(1, sizeof(struct
hashItem));
newKeyValue->hashedKey = (char*)malloc(sizeof(char) * 100);
newKeyValue->hashedValue = (char*)malloc(sizeof(char) * 100);
strcpy(newKeyValue->hashedKey, key);
newKeyValue->hashedValue = value;
newKeyValue->next = NULL;
return newKeyValue;
}
void put(struct hashItem** hashTable, char *key, char *value)
{
if (value == NULL)
return;
struct hashItem *newKeyValue = createNewItem(key, value);
int index = hashf(key);
if (hashTable[index] == NULL){
hashTable[index] = newKeyValue;
}
else
{
int inserted = 0;
struct hashItem *p = hashTable[index];
struct hashItem *q = NULL;
while (p != NULL){
int e = strcmp(p->hashedKey, newKeyValue->hashedKey);
if (e == 0){
if (q != NULL)
q->next = newKeyValue;
p->hashedValue = newKeyValue->hashedValue;
inserted = 1;
break;
}
q = p;
p = p->next;
}
if (!inserted)
q->next = newKeyValue;
}
}
struct hashItem * get(struct hashItem** hashTable, char *key){
if (hashTable == NULL)
return NULL;
int index = hashf(key);
if (hashTable[index] != NULL)
{
if (!strcmp(hashTable[index]->hashedKey, key)){
return hashTable[index];
}
else{
struct hashItem *p = hashTable[index];
while (p != NULL){
if (p->hashedKey == key)
return p;
p = p->next;
}
return NULL;
}
}
else{
return NULL;
}
}
int main(){
hashItem** hashtable = (hashItem**)malloc(sizeof(hashItem*)*20);
for (int i = 0; i < 20; i++){
hashtable[i] = (hashItem*)malloc(sizeof(hashItem));
hashtable[i]->hashedKey = NULL;
hashtable[i]->hashedValue = NULL;
hashtable[i]->next = NULL;
}
put(hashtable, "select", "marks");
hashItem* temp = (hashItem*)get(hashtable,"select");
printf("%s", temp->hashedKey);
int k;
scanf("%d", &k);
return 0;
}
During the debugging it seems the code is crashing at the exact line of:
struct hashItem *p = hashTable[index];
Please tell me why the code is crashing.
Basically you are thinking wrong about initializing the hash buckets.
In the main() function basically you only need to allocate memory for the buckets of the hash table, so you only need this:
hashItem** hashtable = (hashItem**)calloc(20, sizeof(hashItem**));
Pay attention that I am using calloc instead of malloc to make sure that it is going to initialize to NULL these memory region. So, basically here we created 20 buckets to be managed by the hash table.
Again, you should not do that for (int i = 0; i < 20; i++), that is wrong. You will manage the buckets at insertion time, so, when you are inserting something that is not in the hash table, then you allocate memory to that entry.
You are using a mixture of C and C++ here, please make sure to state that when you submit your question.
I will paste here the changes I made, because you were using a lot of casting to get the right pointer type, but it is not necessary if you usce the right structure types.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct _hashItem{
char* hashedKey;
char* hashedValue;
struct _hashItem* next;
} hashItem;
#define SIZE 20
unsigned long hashf(char *str)
{
unsigned long hash = 5381;
int c;
while (c = *str++)
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
return (hash % SIZE);
}
hashItem * createNewItem(char *key, char *value){
hashItem *newKeyValue = (hashItem *)calloc(1, sizeof(
hashItem));
newKeyValue->hashedKey = (char*)malloc(sizeof(char) * 100);
newKeyValue->hashedValue = (char*)malloc(sizeof(char) * 100);
strcpy(newKeyValue->hashedKey, key);
newKeyValue->hashedValue = value;
newKeyValue->next = NULL;
return newKeyValue;
}
void put(hashItem** hashTable, char *key, char *value)
{
if (value == NULL)
return;
hashItem *newKeyValue = createNewItem(key, value);
int index = hashf(key);
if (hashTable[index] == NULL){
hashTable[index] = newKeyValue;
}
else
{
int inserted = 0;
hashItem *p = hashTable[index];
hashItem *q = NULL;
while (p != NULL){
int e = strcmp(p->hashedKey, newKeyValue->hashedKey);
if (e == 0){
if (q != NULL)
q->next = newKeyValue;
p->hashedValue = newKeyValue->hashedValue;
inserted = 1;
break;
}
q = p;
p = p->next;
}
if (!inserted)
q->next = newKeyValue;
}
}
hashItem * get(hashItem** hashTable, char *kAey){
if (hashTable == NULL)
return NULL;
int index = hashf(key);
if (hashTable[index] != NULL)
{
if (!strcmp(hashTable[index]->hashedKey, key)){
return hashTable[index];
}
else{
hashItem *p = hashTable[index];
while (p != NULL){
if (p->hashedKey == key)
return p;
p = p->next;
}
return NULL;
}
}
else{
return NULL;
}
}
int main(){
hashItem** hashtable = (hashItem**)calloc(20, sizeof(hashItem**));
put(hashtable, "select", "marks");
hashItem* temp = get(hashtable,"select");
printf("%s", temp->hashedKey);
int k;
scanf("%d", &k);
return 0;
}

Segmentation fault for a weird unknown reason

I get a segmentation fault (core dumped) in the following peace of code (I'm implementing malloc(), free() and realloc()):
void free(void* ptr)
{
void* curr = head;
void* before = NULL;
int isLegal = 0;
/*Line X*/printf("curr is %p and ptr is %p\n", curr, ptr);
if(curr == ptr)
{
printf("aaa");
}
else
{
printf("bbb");
}
/*Some more code that actually frees the pointer and not relevant here*/
}
Now, you'd assume that it'd print aaa or bbb, it just announces a segmentation fault right after performing the printf() in line X. If I type "printf("a")" instead of the current printf() it won't print 'a' at all. That is really weird.
It prints:
curr is 0x86be000 and ptr is 0x86be000
and yet it would just exit and throw a segmentation fault right after.
The variable head is a static variable in that file. I really want to know where the problem is, it's really weird. Here's the statement from the header file:
void free(void* ptr);
As simple as that, do you see any problem in here?
The full code is available here but I doubt it's related, the program should, at least, print either 'aaa' or 'bbb', and it doesn't do that.
Any idea? I'm really desperate.
Following code complied with warnings but did execute perfectly
#include <unistd.h>
typedef struct metadata_block* p_block;
typedef struct metadata_block
{
size_t size;
p_block next;
int free;
}metadata_block;
void* malloc(size_t size);
void free(void* ptr);
void* realloc(void* ptr, size_t size);
//THE MAIN CODE IS AT THE BOTTOM//
#include <stdio.h>
static p_block head = NULL;
void* malloc(size_t size)
{
void* ptr;
int isOk = 1;
int temp = 0;
p_block curr = head;
if(size <= 0)
{
return NULL;
}
if(curr)
{
while(curr->next && isOk)
{
if(curr->free && size <= curr->size)
{
isOk = 0;
}
if(isOk)
{
curr = curr->next;
}
}
if(isOk) //what will happen if there isn't one free and big enough
{
ptr = sbrk(size + sizeof(metadata_block));
if((int)ptr <= 0)
return NULL;
((p_block)(ptr))->size = size;
((p_block)(ptr))->next = NULL; //next run it's the real next.
((p_block)(ptr))->free = 0;
return (ptr + sizeof(metadata_block));
}
else
{
if(curr->next)
{
ptr = curr;
if(curr->size == size || size > (curr->size - sizeof(metadata_block) - 1)) //not enough room for another block of memory
{
((p_block)(ptr))->free = 0;
return (ptr + sizeof(metadata_block));
}
temp = curr->size;
((p_block)(ptr))->size = size;
((p_block)(ptr))->free = 0;
((p_block)(ptr + sizeof(metadata_block) + size))->next = curr->next;
((p_block)(ptr))->next = ptr + sizeof(metadata_block) + size;
((p_block)(ptr + sizeof(metadata_block) + size))->size = temp - size;
((p_block)(ptr + sizeof(metadata_block) + size))->free = 1;
return (ptr + sizeof(metadata_block));
}
else
{
ptr = curr;
if((int)sbrk(size - curr->size) > 0)
{
((p_block)(ptr))->size = size;
((p_block)(ptr))->next = NULL; //next run it's the real next.
((p_block)(ptr))->free = 0;
return (ptr + sizeof(metadata_block));
}
return NULL;
}
}
}
else
{
ptr = sbrk(size + sizeof(metadata_block));
if((int)ptr <= 0)
return NULL;
head = ptr;
((p_block)(ptr))->size = size;
((p_block)(ptr))->next = NULL;
((p_block)(ptr))->free = 0;
}
return ptr;
}
void free(void* ptr)
{
void* curr = head;
void* before = NULL;
int isLegal = 0;
printf("curr is %p and ptr is %p\n", curr, ptr);
if(curr == ptr)
{
printf("aaa\n");
}
else
{
printf("bbb\n");
}
if(curr && ptr)
{
while(curr && !isLegal)
{
if(((p_block)(ptr)) == ((p_block)(curr))->next)
{
before = curr;
isLegal = 1;
curr = ((p_block)(curr))->next;
}
else
{
curr = ((p_block)(curr))->next;
}
}
if(isLegal)
{
curr = curr - sizeof(metadata_block);
if(((p_block)(curr))->next)
{
((p_block)(curr))->free = 1;
}
else
{
sbrk(0-(((p_block)(curr))->size + sizeof(metadata_block)));
((p_block)(before))->next = NULL;
}
}
}
}
void* realloc(void* ptr, size_t size)
{
void* ptr2 = malloc(size);
int i;
for(i = 0 ; i < size ; i++)
{
*((char*)(ptr2 + i)) = *((char*)(ptr + i));
}
free(ptr);
return ptr2;
}
int main()
{
printf("I'm in.\n");
char * str = malloc(10);
printf("After Malloc()\n");
void * ptr = (void *) str;
void * ptr2;
if(!str)
{
printf("Fail.\n");
}
strcpy(str,"TEST!\0");
printf("About to free\n");
free(str);
printf("free: OK!\n");
}
Output :
I'm in.
After Malloc()
About to free
curr is 0x1049000 and ptr is 0x1049000
aaafree: OK!
note - Instaed of your mm.h include I included codes in same file

C array being overwritten/deleted? very confused

I am working on a project in C and it is working great except for one function which seems to be overwriting my array and writing weird numbers such as 1970802352 which keeps count of word occurrences in a file
this is my header file:
#ifndef LIST_H
#define LIST_H
struct Node_{
char* word;
//array holding names of files word occurs in
char **filesIn;
int numFilesIn;
//array holding count of how many times word occured in file
int* occursIn;
struct Node_ *next;
int isHead;
};
typedef struct Node_ Node;
int insert(char *wordToAdd, char *File);
int addOccur(Node *addedTo, char *File);
Node *createNode(char *wordToAdd, char *File);
void destroyNodes();
#endif
and this is the function that keeps overwriting the array:
Node *head;
int insert(char *wordToAdd, char *File){
if(head == NULL){
Node *new;
new = createNode(wordToAdd, File);
new->isHead = 1;
head = new;
return 0;
}
else{
Node *trace;
trace = head;
char *traceWord;
int wordSize;
wordSize = strlen(trace->word);
traceWord = (char*) malloc(wordSize + 1);
strcpy(traceWord, trace->word);
int a =strcmp(wordToAdd, traceWord);
free(traceWord);
if(a == 0){
int b = addOccur(trace, File);
//printf("addOccur returned %d\n", b);
return 0;
}
if(a < 0){
Node *Insert = createNode(wordToAdd, File);
trace->isHead = 0;
Insert->isHead = 1;
Insert->next = trace;
head = Insert;
return 0;
}
else{
Node *backTrace;
backTrace = head;
while(trace->next != NULL){
trace = trace->next;
traceWord = trace->word;
a = strcmp(wordToAdd, traceWord);
if(a < 0){
Node* Insert = createNode(wordToAdd, File);
Insert->next = trace;
backTrace->next = Insert;
return 0;
}
if(a == 0){
addOccur(trace, File);
//free(wordToAdd);
return 0;
}
if(a > 0){
backTrace = trace;
continue;
}
}
Node *Insert = createNode(wordToAdd, File);
trace->next = Insert;
return 0;
}
}
return 1;
}
and the other functions are:
Node* createNode(char *wordToAdd, char *File){
Node *new;
new = (Node*)malloc(sizeof(Node));
memset(new, 0, sizeof(Node));
new->word = wordToAdd;
char **newArray;
newArray = (char**)malloc(sizeof(char*));
newArray[0] = File;
new->filesIn = newArray;
int a[1];
a[0] = 1;
new->occursIn = a;
//new->occursIn[0] = 1;
new->numFilesIn = 1;
return new;
}
int addOccur(Node *addedTo, char *File){
char **fileList = addedTo->filesIn;
char *fileCheck;
int i = 0;
int fileNums = addedTo->numFilesIn;
for(i = 0; i < fileNums; i++){
fileCheck = fileList[i];
if(strcmp(fileCheck, File) == 0){
int *add1;
add1 = addedTo->occursIn;
int j = add1[i];
j++;
add1[i] = j;
return 0;
}
}
int numberOfFilesIn;
numberOfFilesIn = addedTo->numFilesIn;
char **newList = (char**)malloc(sizeof(char*) * numberOfFilesIn + sizeof(char*));
i = 0;
char *dest;
char *src;
for(i = 0; i < numberOfFilesIn; i++){
src = fileList[i];
int len;
len = strlen(src);
dest = (char*)malloc(sizeof(char) * (len + 1));
strcpy(dest, src);
newList[i] = dest;
}
int len2;
len2 = strlen(File);
newList[i] = File;
free(fileList);
int r = addedTo->numFilesIn;
r++;
addedTo->numFilesIn = r;
addedTo->filesIn = newList;
i = 0;
int *g;
g = addedTo->occursIn;
int count2;
count2 = addedTo->numFilesIn;
count2++;
int a[count2];
for(i = 0; i < count2 -1; i++){
a[i] = g[i];
}
a[count2 - 1] = 1;
return 0;
}
When going to gdb i notice that the value of
head->occursIn[0]
changes after the line
wordSize = strlen(trace->word);
and I have no clue why.
In your CreateNode() function, you are not allocating storage for the occursIn array. You are simply declaring a local array within the function and then assigning the occursIn pointer:
int a[1];
a[0] = 1;
new->occursIn = a;
The array a[1] goes away when the createNode function returns, so at that point your occursIn pointer is pointing to a value that is subject to being overwritten.
And even if the storage was allocated correctly in createNode, you've set a fixed size for the array but your whole strategy depends on that array having an element for each file; and in addOccurs you don't do anything to allocate a new larger array for a new file.
You may want to re-evaluate your strategy and switch to using lists instead of arrays.

Invalid pointer address when trying to free

So all I'm trying to do is free a pointer and it just gives me the error 'invalid address'; though the address is clearly valid, as illustrated by the prints I put in. It tries to free the address of the pointer, but still fails. Through valgrind, it gives the error invalid free() saying the address is on thread 1's stack? The code below is runnable; can anyone help?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#define SUCC 1
#define FAIL -1
typedef struct bucket {
char *key;
void *value;
struct bucket *next;
} Bucket;
typedef struct {
int key_count;
int table_size;
void (*free_value)(void *);
Bucket **buckets;
} Table;
extern unsigned int hash_code(const char *key) {
unsigned int hash = 0, i = 0;
while(i < strlen(key)) {
hash ^= ((hash << 3) | (hash >> 29)) + key[i++];
}
return hash;
}
/*Makes copy of string and returns pointer to it*/
char * cpy(const char *str) {
char *new = malloc(sizeof(char *));
if(new)
strcpy(new, str);
return new;
}
int create_table(Table ** table, int table_size, void (*free_value)(void *)) {
*table = malloc(sizeof(Table));
if(table && table_size != 0) {
int i = 0;
(*table)->key_count = 0;
(*table)->table_size = table_size;
(*table)->free_value = free_value;
(*table)->buckets = calloc(table_size, sizeof(Bucket *));
while(i < table_size)
(*table)->buckets[i++] = NULL;
return SUCC;
}
return FAIL;
}
int put(Table * table, const char *key, void *value) {
if(table && key) {
int hash = hash_code(key)%table->table_size;
Bucket *curr = table->buckets[hash];
while(curr) {
if(strcmp(curr->key, key) == 0) {
if(table->free_value)
table->free_value(curr->value);
printf("addr of ptr: %p\n", value);
curr->value = value;
printf("addr of curr ptr: %p\n", curr->value);
return SUCC;
}
curr = curr->next;
}
curr = malloc(sizeof(Bucket));
curr->key = cpy(key);
printf("addr of ptr: %p\n", value);
curr->value = value;
printf("addr of curr ptr: %p\n", curr->value);
curr->next = table->buckets[hash];
table->buckets[hash] = curr;
table->key_count++;
return SUCC;
}
return FAIL;
}
int remove_entry(Table * table, const char *key) {
if(table && key) {
int hash = hash_code(key)%(table->table_size);
Bucket *curr = table->buckets[hash], *prev = table->buckets[hash];
while(curr) {
printf("attempt");
if(strcmp(curr->key, key) == 0) {
void * test = curr->value;
printf("at addr %p\n", test);
table->free_value(test);
printf("freed");
if(table->free_value){
table->free_value(curr->value);
}
free(curr->key);
curr->key = NULL;
curr->value = NULL;
table->key_count--;
if(prev == curr)
table->buckets[hash] = curr->next;
else
prev->next = curr->next;
free(curr);
curr = NULL;
return SUCC;
}
prev = curr;
curr = curr->next;
}
}
return FAIL;
}
And the test file that shows the error:
#include <stdio.h>
#include <stdlib.h>
#include "htable.h"
int main() {
Table *t;
int num2 = 3;
printf("create: %d\n",create_table(&t, 2, free));
printf("addr of ptr: %p\n",(void *)&num2);
printf("put %s: %d\n","test",put(t, "test", &num2));
printf("rem key: %d\n",remove_entry(t, "test"));
return 0;
}
This is broken:
char *new = malloc(sizeof(char *));
The amount of memory you need is based on what you need to store, which is the string. You want:
char *new = malloc(strlen(str) + 1);
Or, better yet, just use strdup.
You are trying to free() a stack variable: num2 (in main()):
int num2 = 3;
Later, you have this call:
printf("put %s: %d\n","test",put(t, "test", &num2));
You're passing the address of num2 to put(), which means that remove_entry() will try to free it later. This is illegal. You cannot free a variable allocated on the stack. You should dynamically allocate num2 instead:
int* num2 = malloc(sizeof(int));
*num2 = 3;
There's another problem as well though. In this code:
void * test = curr->value;
printf("at addr %p\n", test);
table->free_value(test);
printf("freed");
if(table->free_value){
table->free_value(curr->value);
}
You are freeing curr->value twice, because you're freeing test which is just a copy of the pointer.

Resources