memory-managementlinux-kernelkmalloc

Does kmalloc call type constructor?


It is known that memory allocation with new calls respective type constructor and memory allocation with malloc does not. But what about kmalloc?

I am trying to develop some system calls and I need to assign memory to a structure below.

struct mailbox{
    unsigned long existing_messages;
    unsigned long mxid;
    struct message *msg;
    struct message *last_node;
    mailbox(){
        existing_messages = 0;
        mxid = 0;
        msg = NULL;
        last_node  = NULL;
    }
};

If I allocate memory with kmalloc will it call constructor for struct mailbox at allocation time? if not what are the reasonable possible ways to get the constructor called except calling constructor explicitly. Is there any equivalent function as new for memory allocation in kernel?


Solution

  • kmalloc doesn't call constructor.

    one way in C++ is to call "placement new".

    example:

    void* ptr = malloc( sizeof(T) );

    T* p = new (ptr) T(); //construct object in memory

    note: you need to call destructor explicitly to avoid memory leaks in object itself, and then call corresponding de-allocation routine for this memory.

    p->~T(); //call destructor

    free(ptr); //free memory