cmodulelinux-kerneldynamic-arrayskmalloc

Dynamic Array in Linux Kernel Module with kmalloc


I am writing a small program which prints the time it took to allocate the memory. I want to free the memory later so I want to save it in a array, but since I can loop it as many times as I want I want to make a Dynamic array to store all the addresses from the allocated Memory. This is my init code:

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;
}

I Always get these errors: Errors


Solution

  • What is wrong is that you choose char as the element of the array by selecting char* for the type of buffer. The elements of the array should pointers, so buffer should be a pointer to pointers like this (for example):

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

    Use two *s, not one.