Using malloc in C++

B

Bharath

Hi all,

I am trying to use malloc to allocate memory to an object. Something
like:

TestClass *obj = (TestClass *) malloc(sizeof(TestClass));

Its obvious that the constructor doesn't get called in the above case,
nor the destructor when I free it.

Is there a way that I can invoke the constructor after the malloc
statement?

I believe that's what 'new' does isn't it? It allocates memory and
then invokes the constructor.

Thanks,
-Bharath
 
F

Francesco S. Carta

Hi all,

I am trying to use malloc to allocate memory to an object. Something
like:

TestClass *obj = (TestClass *) malloc(sizeof(TestClass));


Don't do that, avoid C style casts and malloc, simply call...

TestClass* obj = new TestClass;

....and let the computer do all the rest for you (allocating memory,
calling ctors and dtors etc) - of course, you might need to call
"delete" on that obj somewhere...
 
B

Bharath

#include <iostream>
#include <memory>

struct X
{
        X()     { std::cout << "X()\n"; }
        ~X()    { std::cout << "~X()\n"; }

};

void test_malloc()
{
        X *p = static_cast<X*>(malloc(sizeof(X)));
        new (p) X;
        p->~X();
        free(p);

}

void test_operator_new()
{
        X *p = static_cast<X*>:):eek:perator new(sizeof(X)));
        new (p) X;
        p->~X();
        ::eek:perator delete(p);

}

void test_new()
{
        X *p = new X;
        delete p;

}

int main()
{
        test_malloc();
        test_operator_new();
        test_new();
        return 0;

}

Cheers,
Stu

Wow Stu, that clears up the confusion. I had an idea that I had to use
the new operator to call the constructor again, but wasn't sure how.

Thanks,
-Bharath
 
R

red floyd

[placement new example redacted]

Wow Stu, that clears up the confusion. I had an idea that I had to use
the new operator to call the constructor again, but wasn't sure how.
Bharath,

I'm guessing you're just learning the language.

Stu's example works, but DO NOT WRITE CODE LIKE THAT!!!! It's a
workaround
if you *must* use malloc/free because of legacy code. If at all
possible,
don't use malloc/free, but instead use new/delete. New has the
following
advantages:

* Will automatically construct the object
* Will never return NULL, but will instead throw std::bad_alloc
* No cast from void* is required.


Similarly, delete will automatically destruct objects allocated by
new.
 
R

red floyd

red said:
[placement new example redacted]
Wow Stu, that clears up the confusion. I had an idea that I had to use
the new operator to call the constructor again, but wasn't sure how.

I'm guessing you're just learning the language.
Stu's example works, but DO NOT WRITE CODE LIKE THAT!!!!  It's a
workaround
if you *must* use malloc/free because of legacy code.  If at all
possible,
don't use malloc/free, but instead use new/delete.  New has the
following
advantages:
* Will automatically construct the object
* Will never return NULL, but will instead throw std::bad_alloc
* No cast from void* is required.
Similarly, delete will automatically destruct objects allocated by
new.

There are occasionally valid reasons to do this sort of thing (I seem to
recall the Phoenix singleton implementation used this), but you're right
that it's one to avoid in most situations.

Oh definitely. But the OP looks like a newbie, and I doubt he's
working with
Phoenix singletons.
 
B

Bharath

red said:
[placement new example redacted]
Wow Stu, that clears up the confusion. I had an idea that I had to use
the new operator to call the constructor again, but wasn't sure how.
Bharath,
I'm guessing you're just learning the language.
Stu's example works, but DO NOT WRITE CODE LIKE THAT!!!!  It's a
workaround
if you *must* use malloc/free because of legacy code.  If at all
possible,
don't use malloc/free, but instead use new/delete.  New has the
following
advantages:
* Will automatically construct the object
* Will never return NULL, but will instead throw std::bad_alloc
* No cast from void* is required.
Similarly, delete will automatically destruct objects allocated by
new.
There are occasionally valid reasons to do this sort of thing (I seem to
recall the Phoenix singleton implementation used this), but you're right
that it's one to avoid in most situations.

Oh definitely.  But the OP looks like a newbie, and I doubt he's
working with
Phoenix singletons.

Well, I am aware of why to use new/delete and not malloc/free. I just
wanted to know how to call the constructor if allocated with malloc.

Thanks,
-Bharath
 
J

J Cook

Well, I am aware of why to use new/delete and not malloc/free. I just
wanted to know how to call the constructor if allocated with malloc.

And the answer you are overwhelmingly hearing is "Don't do that"
unless you want broken code or have an exceptionally good reason. If
you were asked on a job interview how to do this, the most impressive
first answer would be to say "You don't do that" and then the reasons
why.

If you were asking for purely intellectual pursuits, then I highly
recommend reading the C++ FAQ where you will be stimulated beyond
reason . :)
 
J

James Kanze

"red floyd" <[email protected]> ha scritto nel
messaggio
[placement new example redacted]
Wow Stu, that clears up the confusion. I had an idea that I
had to use the new operator to call the constructor again,
but wasn't sure how.
Stu's example works, but DO NOT WRITE CODE LIKE THAT!!!!

It depends on what you're doing (although I'd suggest using the
operator new/operator delete functions instead of malloc/free).
There are a number of cases where you want to separate
allocation and initialization.
It's a workaround if you *must* use malloc/free because of
legacy code.

No. It's a means of separating allocation from initialization.
It should be used in almost all container classes, for example,
and in things like Fallible or Variant.
If at all possible, don't use malloc/free, but instead use
new/delete. New has the following advantages:
* Will automatically construct the object

Which is fine when that's what you want.
?malloc too construct object it only not initialize it

Neither malloc nor the operator new function construct the
object. (In C++, "construct" and "initialize" are practically
synonyms.)
* Will never return NULL, but will instead throw std::bad_alloc
?you call that one advantage?

Usually. Never returning NULL is definitely an advantage. And
throwing an exception is only the default behavior---you can
easily override it to abort the process if that's preferrable
(which it often is).

Of course, the operator new function has these advantages as
well.
 
J

James Kanze

"James Kanze" <> ha scritto nel
messaggionews:457b6fc5-4d9a-448b-af5b-ca10db4fa35b@a30g2000yqn.googlegroups.com...
"red floyd" <[email protected]> ha scritto nel
messaggio[placement new example redacted]
* Will automatically construct the object
Which is fine when that's what you want.
?malloc too construct object it only not initialize it
Neither malloc nor the operator new function construct the
object. (In C++, "construct" and "initialize" are practically
synonyms.)
"construct" is not a "initialize" synonyms

It is when you're talking about C++. The constructor
"initializes" the object, and a constructed object is an
"initialized" object.
i would know if there is
int x;
x is "construct" [reserve the memory] but not initialized
in others words how do you would say that?

In this case, I might agree, although the C++ standard will
sometimes speak of x being initialized to an indeterminate (and
possibly invalid) value.

The important distinction is that a "constructed" (or
"initialized") object has the type of the object. If a type has
a non-trivial constructor, an object of that type doesn't start
to exist type until it has been constructed (or
initialized---the C++ standard often uses the two words
indiscriminately). Before the object is constructed, all you
have is raw memory. malloc and the operator new function return
raw memory; a new expression creates an (initialized) object.
so for you reserve the memory for one object type
(int, double, structs, classes) is not construct it?

Reserving the memory doesn't construct an object. It just
reserves raw memory. In the case of a type with a trivial
constructor, the lifetime of the object begins as soon as the
memory has been allocated. In the case of a type with
a non-trivial constructor, the lifetime of the object doesn't
begin until the constructor call is complete.
i would spell that in this way:
"initialize object" == write the memory of the object the first time
"construct object" == reserve the memory for the object

You could. But then you wouldn't be talking about C++.
 
N

Nick Keighley

Wow Stu, that clears up the confusion. I had an idea that I had to use
the new operator to call the constructor again, but wasn't sure how.

it isn't calling it again. Its invoking it once. You don't want it to
call it again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Alternative to Malloc in C 0
malloc problem in C++ 13
malloc 40
malloc and maximum size 56
Using malloc in C++? 71
malloc() fail 10
In-consistent behavior in malloc/free . 1
using my own malloc() 14

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top