今天遇到一下奇怪的段错误,研究发现原来是内存写越界了。
函数片段如下 ht_insert_he --> ht_index --> hashfunction
void
ht_insert_he(hash_table *table, hash_entry *entry)
{
hash_entry *tmp;
unsigned int index;
entry->timestamp = time(NULL);
entry->next = NULL;
index = ht_index(table, entry->key, entry->key_size);
tmp = table->array[index]; //段错误出现位置
......
}unsigned int
ht_index(hash_table *table, void *key, size_t key_size)
{
uint32_t index; //32位变量
table->hashfunction(key, key_size, global_seed, &index);
index %= table->array_size;
return index;
}其中hashfunction实现如下
void
hashfunction(const void *key, const int len, const uint32_t seed, void *out)
{
const uint8_t * data = (const uint8_t*)key;
const int nblocks = len / 16;
......
((uint64_t*)out)[0] = h1; //把最后一个参数当64位进行写操作
((uint64_t*)out)[1] = h2;
}!!!把32位变量index的地址传给了hashfunction,而hashfunction把它当成了64位变量进行写入,破坏了函数栈。