你好,游客 登录 注册 搜索
背景:
阅读新闻

Linux 内核链表移植

[日期:2013-06-20] 来源:Linux社区  作者:cheungmine [字体:大 中 小]

测试程序(Windows, C++):

/**
 * test dhlist
 * cheungmine
 */
#define _CRTDBG_MAP_ALLOC   
#include<stdlib.h> 
#include<crtdbg.h>

#include <assert.h>
#include <stdio.h>
#include <string.h>
#include <memory.h>

#include <windows.h>

#include "dhlist.h"

struct ST {
    unsigned char ch;
    int  this_data;
   
  struct list_head  i_list;
   
    int  more_data;
   
  struct hlist_node i_hash;

    char str_data[32];
    int end_data;
} *st;

#define HASHSIZE 0xff
#define LISTSIZE 4096

struct list_head list1; 
struct hlist_head hlist[HASHSIZE+1];

unsigned int gethash(int c)
{
    return (c & HASHSIZE);
}

int main()
{
    int i;
    unsigned int hash;
    struct list_head *list, *node;
    struct hlist_node *hp;
    struct hlist_node *hn;

    INIT_LIST_HEAD(&list1);

    for (hash = 0; hash <= HASHSIZE; hash++) {
        INIT_HLIST_HEAD(&hlist[hash]);
    }

    for(i = 0; i < LISTSIZE; i++) {
        struct ST *p = (ST*) malloc(sizeof(*p));
        if(!p) {
            printf("malloc failed.\n");
            break;
        }

        p->ch = 'a' + i;
        sprintf(p->str_data, "data:%d", i);

        // 串入长串
        list_add(&p->i_list, &list1);

        // 串入HASH短串
        hash = gethash(p->ch);

        printf("ALLOC %x %d %p %u\n", p->ch, i, p, hash);

        if (hash > HASHSIZE) {
          printf("**********ERROR**********\n");
        } else {
          hlist_add_head(&p->i_hash, &hlist[hash]);
        }
    }

    // 通过长铁丝遍历
    i = 0;
    list_for_each(list, &list1) {
        struct ST *p = list_entry(list, struct ST, i_list);
        printf("%p  value %d = %d\n", p, i, (int)p->ch);
        i++;
    }
    printf("total %d \n", i);

    printf("通过hash串查找内容'C'的箱子\n");
    hash = gethash('c');
    hlist_for_each(hp, &hlist[hash]) {
        struct ST *p = hlist_entry(hp, struct ST, i_hash);
        printf("hlist: %c\n", p->ch);
    }

    printf("通过hash串查找内容'C'的箱子并删除之\n");
    hlist_for_each_safe(hp, hn, &hlist[hash]) {
        struct ST *p = hlist_entry(hp, struct ST, i_hash);
        printf("hlist_del: %c; %s\n", p->ch, p->str_data);
        hlist_del(hp);
    }

    printf("通过hash串查找内容'C'的箱子\n");
    hlist_for_each(hp, &hlist[hash]) {
        struct ST *p = hlist_entry(hp, struct ST, i_hash);
        printf("hlist: %c\n", p->ch);
    }

    printf("删除全部节点箱子\n");
    list_for_each_safe(list, node, &list1) {
        struct ST *p = list_entry(list, struct ST, i_list);
        list_del(list);
        free(p);
    }

    // 检测内存泄露
    _CrtDumpMemoryLeaks();
    return 0;
}

linux
相关资讯       Linux内核链表  内核链表 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款