C语言 我如何使用list_for_each宏在list.h(从Linux内核)正确



我很难使用Linux内核中的list.h为我的代码提供链表功能。我怀疑我几乎有函数代码,但我在某个地方混淆了指针。

如何正确使用list_for_each宏?在我的代码中,它被困在一个无限循环中,没有退出列表。下面是问题所在的代码片段(查看add_kv函数):

dict_entry *alloc_dict(void)
{
    //allocates the linked list head node
    dict_entry *d = malloc(sizeof(dict_entry));
    INIT_LIST_HEAD(&d->list);
    return d;
}
 
void free_dict(dict_entry *d)
{
    //TODO: free each dict_entry struct and their keys and values.
    free(d);
}
int add_kv(dict_entry *d, char *key, char *value)
{
    if(!key || !d) return 0; //if key or d is null, return 0
    struct list_head *p; //serves as the cursor
    dict_entry *entry; //empty dict_entry
    entry = alloc_dict(); //allocate memory for it
    list_for_each(p, &d->list){
        d = list_entry(p, dict_entry, list); //CHANGED TO d FROM entry
        printf("gothere, p = %pn",p); // something in here is creating an infinite loop. p is moving back and forth. this is the big problem in this code
        if(strcmp(entry->key, key) == 0){
            free(entry->value);
            entry->value = 0;
            entry->value = malloc(strlen(value));
            strcpy(entry->value, value);
            return 1; //how do i get rid of entry?
        }
    }
    //If you haven't returned by now, continue on to add a new entry at the end of the list 
    entry->key = malloc(strlen(key)); //allocate memory for the key
    strcpy(entry->key, key); //copy the key value to the key in the entry
    entry->value = malloc(strlen(value)); //allocate memory for value
    strcpy(entry->value, value); //copy value value to the value in the entry
 
    list_add(&entry->list,&d->list); //tacks the list of the new entry onto the existing list (provided as d)
    return 1;
}
下面是list.h中的list_for_each宏,供参考:
/**
 * list_for_each    -   iterate over a list
 * @pos:    the &struct list_head to use as a loop cursor.
 * @head:   the head for your list.
 */
#define list_for_each(pos, head) 
    for (pos = (head)->next; pos != (head); pos = pos->next)

下面是list.h中的list_entry宏,同样供参考:

/**
 * list_entry - get the struct for this entry
 * @ptr:    the &struct list_head pointer.
 * @type:   the type of the struct this is embedded in.
 * @member: the name of the list_struct within the struct.
 */
#define list_entry(ptr, type, member) 
    container_of(ptr, type, member)

…和我使用的dict_entry结构体:

  6 typedef struct {
  7   char *key;
  8   char *value;
  9   struct list_head list;
 10 }dict_entry;

…当运行时,会发生如下情况:

gothere, p = 0x1178050
gothere, p = 0x1178020
gothere, p = 0x1178050
gothere, p = 0x1178020

一遍又一遍

关于如何使用list.h实现列表的一个很好的解释可以在这里找到参考。

由于某种原因,您正在重新分配变量d,这会破坏list_for_each宏。

你有这样的代码:

list_for_each(p, &d->list){
    d = list_entry(p, dict_entry, list);

宏在每次迭代中重新计算&d->list,以查看何时到达列表结束。由于d被重新分配,此检查失败并永远循环。

相关内容

  • 没有找到相关文章