Reputation: 11
int level
has Invalid read of size 4
, and valgrind shows Memcheck, a memory error detector
.void sl_set(leapList *head, int *key, int *value) {
leapList *prev[MAX_SKIPLIST_HEIGHT];
leapList *curr = head;
int level = head->height - 1;
// Find the position where the key is expected
while (curr != NULL && level >= 0) {
prev[level] = curr;
if (curr->next[level] == NULL) {
-- level;
} else {
//int cmp = strcmp(curr->next[level]->key, key);
//if (cmp == 0) {
if ((curr->next[level]->key) == key) {
// Found a match, replace the old value
free(curr->next[level]->value);
curr->next[level]->value = value;
return;
} else if ((curr->next[level]->key) > key) { // Drop down a level
-- level;
} else { // Keep going at this level
curr = curr->next[level];
}
}
}
// Didn't find it, we need to insert a new entry
leapList *new_entry = malloc(sizeof(leapList));
new_entry->height = grand(head->height);
new_entry->key = key;
new_entry->value = value;
int i;
// Null out pointers above height
for (i = MAX_SKIPLIST_HEIGHT - 1; i > new_entry->height; --i) {
new_entry->next[i] = NULL;
}
// Tie in other pointers
for (i = new_entry->height - 1; i >= 0; -- i) {
new_entry->next[i] = prev[i]->next[i];
sOw code as codeprev[i]->next[i] = new_entry;
}
}
Upvotes: 0
Views: 450
Reputation: 144959
For int level = head->height - 1;
to produce an invalid read of size 4
, there can be only one explanation: the pointer head
is invalid and you have undefined behavior.
head
is a null pointer, but this should produce a segmentation fault,head
is uninitialized, but again a segmentation fault would be highly likely,head
points to a previously freed memory block or an object that has gone out of scope: valgrind detects this condition as the pointer should not be dereferenced but if the memory it points to is readable, the CPU might not generate an error, just meaningless data is read.Look at the calling code and investigate where head
is coming from.
Upvotes: 3