0

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?

user3508953
  • 427
  • 6
  • 15
  • Wait, how are you using C++ in the Linux Kernel? There's no such thing as constructors in C. Your code shouldn't even compile! – tangrs Sep 08 '14 at 16:07
  • In kernel main make file I see a line **HOSTCXX = g++ HOSTCXXFLAGS = -O2** this means that when kernel compiles it is capable of compiling c++ code, Am I right? Please correct me if I am wrong. – user3508953 Sep 09 '14 at 01:23
  • I highly doubt you would have much success... Sure, you might be able to get it to compile but I doubt you'd get anything useful out of it. The kernel doesn't support the C++ runtime AFAIK. – tangrs Sep 09 '14 at 03:14

1 Answers1

2

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

Community
  • 1
  • 1
crazii
  • 311
  • 1
  • 6