我在局部变量上使用 uthash 时遇到了一些问题。
我的代码看起来像这样,query_dict 是一个局部变量 uthash:
main functions:
query* query_dict = NULL;
split_query_into_terms(querystr, &query_dict);
print_query_struct(&query_dict);
prefetch_tokens(&query_dict);
接近一点了:
void prefetch_tokens(query** query_dict) {
query* entry;
for(entry=*query_dict; entry != NULL; entry=entry->hh.next) {
handle_token(entry->term);
}
}
void add_term_to_query(query** query_dict, char* term, dictionary_entry* dict_entry) {
// if query in hashtable, increase score:
query* myq = NULL;
if(*query_dict != NULL)
HASH_FIND_STR(*query_dict, term, myq);
if(myq == NULL) {
myq = init_alloc_query(term);
myq->dict_entry = dict_entry;
HASH_ADD_KEYPTR(hh, *query_dict, myq->term, strlen(myq->term), myq);
} else {
myq->score += 1.0f;
}
}
void split_query_into_terms(char* querystr, query** query_dict) {
char* myquery = strdup(querystr);
char* reentrant_saver;
char* token;
token = strtok_r(myquery, " \n", &reentrant_saver);
while(token != NULL) {
dictionary_entry* dict_entry = find_dict_entry(token);
if(dict_entry) {
add_term_to_query(query_dict, token, dict_entry);
}
token = strtok_r(NULL, " \n", &reentrant_saver);
}
}
void print_query_struct(query** query_dict) {
query* entry;
for(entry=*query_dict; entry != NULL; entry=entry->hh.next) {
fprintf(stdout, "%s: %f\n", entry->term, entry->score);
}
}
对 print_query_struct 的调用运行良好,但对预取令牌的调用执行一次迭代,然后崩溃:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000001000000000
0x0000000100004959 in prefetch_tokens (query_dict=0x7fff5fbffa30) at search/c_port/search.c:241
241 handle_token(entry->term);
(gdb) bt
0 0x0000000100004959 in prefetch_tokens (query_dict=0x7fff5fbffa30) at search/search.c:241
1 0x00000001000049d2 in search (querystr=0x7fff5fbffbe5 "wash") at search/search.c:255
2 0x0000000100004a20 in main (argc=2, argv=0x7fff5fbffa80) at search/search.c:263
地址,0x0000001000000000 总是相同的。
我一直在尝试各种不同的东西,但无法让它发挥作用。这里有人知道发生了什么吗?
结构:
typedef struct {
char* word;
uint32_t byte_offset;
uint32_t occurences;
uint32_t occurences_abstract;
postings_entry* posting;
UT_hash_handle hh; /* makes this structure hashable */
} dictionary_entry;
/* query has a number of terms (strings) */
typedef struct {
char* term;
float score;
dictionary_entry* dict_entry;
UT_hash_handle hh;
} query;
编辑:我已经简化了代码并制作了一个较小的可运行示例,但本质上,这是失败的代码:http: //pastebin.com/qdDiQMG0 编译,然后使用 ./binary 运行
例如。./binary "清洗帮助"
编辑2:即使我不太明白它为什么起作用,也解决了它:从以下位置重写了init_alloc_query:
query* init_alloc_query() {
query* query = malloc(sizeof(query));
query->term = NULL;
return query;
}
像这样工作:
void init_alloc_query(query** q) {
*q = malloc(sizeof(query));
(*q)->term = NULL;
}
一切运行良好。