【问题标题】:Dynamic Array in Linux Kernel Module with kmalloc带有 kmalloc 的 Linux 内核模块中的动态数组
【发布时间】:2021-07-28 22:14:17
【问题描述】:

我正在编写一个小程序来打印分配内存所花费的时间。 我想稍后释放内存,所以我想将它保存在一个数组中,但是由于我可以循环多次,我想创建一个动态数组来存储分配的内存中的所有地址。这是我的 初始化代码:

static __init int init_kmalloc(void)
{
    int size = sizeof(char*);
    char *buffer = kmalloc_array(loop_cnt, size, GFP_KERNEL);
    unsigned int i = 0;

    printk(KERN_DEBUG "Allocating %d times the memory size of %d\n", loop_cnt, alloc_size);
    while(i < loop_cnt)
    {
        unsigned long long start;
        unsigned long long stop;

        start = get_rdtsc();
        buffer[i] = kmalloc(alloc_size, GFP_KERNEL);
        stop = get_rdtsc();

        printk(KERN_DEBUG "%i: It took %lld ticks to allocate the memory\n", i, stop - start);
        i++;
    }

    while(i > 0)
    {
        kfree(buffer[i]);
        printk(KERN_DEBUG "Cleared\n");
        i--;
    }

    return 0;
}

我总是收到以下错误:

【问题讨论】:

标签: c module linux-kernel dynamic-arrays kmalloc


【解决方案1】:

错在你选择char作为数组的元素是通过选择char*作为buffer的类型。数组的元素应该是指针,所以buffer 应该是指向这样的指针的指针(例如):

char **buffer = kmalloc_array(loop_cnt, size, GFP_KERNEL);

使用两个*s,而不是一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 2012-04-11
    • 2013-12-17
    • 1970-01-01
    相关资源
    最近更新 更多