Reputation: 434
just noticed some weird behavior, can anyone explain and tell me what I'm doing wrong?
I want to implement a Hashset using an array of linked list pointers using C, however, when I add my linked list node, the data value only gets updated if I print it out first.
Here's my code:
#include <stdio.h>
#define print(ref) printf(#ref" = %d\n",ref);
#define HASH_MODULE 13
typedef struct listNode{
int data;
struct listNode*next;
}listNode;
void addToSet(int,listNode**);
int hashCode(int);
int main(){
listNode*linkedListHashset[HASH_MODULE];
addToSet(10,linkedListHashset);
print(linkedListHashset[10]->data);
return 0;
}
void addToSet(int value, listNode**set){
int bucket = hashCode(value);
print(bucket);
listNode newNode = {value};
newNode.next = set[bucket];
set[bucket] = &newNode;
//print(set[bucket]->data);
}
int hashCode(int value){
return value%HASH_MODULE;
}
You can see there's a commented out line, if I compile it like this, the value won't get stored, giving this output (which is not what I would expect):
bucket = 10
linkedListHashset[10]->data = 0
However, when I include the commented out line here's the output, it does reflect the desired update, here the data at the pointer behaves as I expected:
bucket = 10
set[bucket]->data = 10
linkedListHashset[10]->data = 10
I'm thinking this might be a compiler artifact or something, I compile by doing:
$gcc -Wall -Werror -O -o source.c
Therefore no warnings, everything seems in order. What do you think? What am I missing?
Upvotes: 0
Views: 31
Reputation: 48647
In addToSet
, you're declaring newNode
on the stack, then storing its address in set[bucket]
and returning. It then becomes a dangling pointer, which leads to undefined behavior when you dereference it in main
.
Upvotes: 1