473,587 Members | 2,580 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

differences between malloc and operator new..

Hi..
I'm so sorry about that I've postes so many questions recently.. :)

I'm still confused about the differences between malloc and operator new..
I know that when we work with class object and use operator new/delete, the
ctor and dtor
get called as expected, but malloc and free do not..

But Herbal Sutter mentioned in his greate book 'exceptional c++' about free
storage
and heap..
He said they are differenct and we need to know the differences..

But I'm still confused about they are different..
I've thought actually both new and malloc use heap..

can some clearify me?
Jul 22 '05 #1
22 2562

"BekTek" <be****@gmail.c om> wrote in message
news:ZNsqd.2517 $wr6.2059@trndd c04...
Hi.. But Herbal Sutter mentioned in his greate book 'exceptional c++' about free


I don't think "Herb" is short for "Herbal" in this case ;-)

Jonathan
Jul 22 '05 #2

"Jonathan Turkanis" <te******@kanga roologic.com> wrote in message
news:30******** *****@uni-berlin.de...

"BekTek" <be****@gmail.c om> wrote in message
news:ZNsqd.2517 $wr6.2059@trndd c04...
Hi..
But Herbal Sutter mentioned in his greate book 'exceptional c++' about

free
I don't think "Herb" is short for "Herbal" in this case ;-)

sorry, my mistake :)
Jonathan

Jul 22 '05 #3
BekTek wrote:
....

can some clearify me?


This is an example where the global operator new is overridden...

#include <iostream>
#include <string>

using namespace std;

void * operator new( size_t size )
{
cout << "our own new operator -- size is " << size << "\n";
return malloc( size );
}

void operator delete( void *pFreeMe )
{
cout << "our own delete operator\n";
free( pFreeMe );
}

class CA
{
public:

CA( std::string strArg ) : strString( strArg )
{
}

void print()
{
cout << strString.c_str () << "\n";
}

private:

std::string strString;
};

int main( int iArgc, char *pcArgv[] )
{
CA *pa = new CA( "funky" );
pa->print();

cout << sizeof( CA ) << "\n";

delete pa;
}
Jul 22 '05 #4

"Gianni Mariani" <gi*******@mari ani.ws> wrote in message
news:BK******** ************@sp eakeasy.net...
BekTek wrote:
...

can some clearify me?


This is an example where the global operator new is overridden...

#include <iostream>
#include <string>

using namespace std;

void * operator new( size_t size )
{
cout << "our own new operator -- size is " << size << "\n";
return malloc( size );
}

void operator delete( void *pFreeMe )
{
cout << "our own delete operator\n";
free( pFreeMe );
}

class CA
{
public:

CA( std::string strArg ) : strString( strArg )
{
}

void print()
{
cout << strString.c_str () << "\n";
}

private:

std::string strString;
};

int main( int iArgc, char *pcArgv[] )
{
CA *pa = new CA( "funky" );
pa->print();

cout << sizeof( CA ) << "\n";

delete pa;
}


Sorry, but I'm a bit confused. How/why does the constructor for class CA get
called if new is overriden? What order would they be called in (I assume:
operator new then ctor)?

Also, I don't know if the above is a good example, because it doesn't really
illustrate why someone would want to override new.
Jul 22 '05 #5
"Method Man" <a@b.c> wrote in message news:cE******** **********@read 1.cgocable.net. ..

"Gianni Mariani" <gi*******@mari ani.ws> wrote in message
news:BK******** ************@sp eakeasy.net... ....
This is an example where the global operator new is overridden...

#include <iostream>
#include <string>

using namespace std;

void * operator new( size_t size )
{
cout << "our own new operator -- size is " << size << "\n";
return malloc( size );
}

void operator delete( void *pFreeMe )
{
cout << "our own delete operator\n";
free( pFreeMe );
}

class CA
{
public:

CA( std::string strArg ) : strString( strArg )
{
}

void print()
{
cout << strString.c_str () << "\n";
}

private:

std::string strString;
};

int main( int iArgc, char *pcArgv[] )
{
CA *pa = new CA( "funky" );
pa->print();

cout << sizeof( CA ) << "\n";

delete pa;
}


Sorry, but I'm a bit confused. How/why does the constructor for class CA get
called if new is overriden?


The constructor is called in the same way as is usual, after
a location for the object has been determined or arranged.
Why is it called? To convert raw memory into a proper
instance of the class. This is the constructor's role, to be
distinguished from somehow obtaining raw memory.
What order would they be called in (I assume:
operator new then ctor)?
Yes.
Also, I don't know if the above is a good example, because it doesn't really
illustrate why someone would want to override new.


True, it only illustrates the mechanics of overriding and
shows that the ctor is called after operator new works.
It takes a little more imagination to see that the ability
to define a customized or optimized allocator can be
used to improve the performance of programs. For
example, if it was known in advance that allocations
tended to all occur before releases, a simpler and
hence faster allocator could be written.

A more common override is to define a per-class
operator new and delete. Such an allocator can be
specialized for objects of a certain size which can
permit considerably faster operation.

--
--Larry Brasfield
email: do************* **********@hotm ail.com
Above views may belong only to me.
Jul 22 '05 #6
BekTek wrote:
I'm still confused about the differences between malloc and operator new..
I know that when we work with class object and use operator new/delete, the
ctor and dtor
get called as expected, but malloc and free do not..
There is a difference between operator new and the new operator: the
latter calls the former.

The new operator is something you will never see. Basically, it does
two things :

1. calls operator new to get some raw memory
2. calls the object's constructor on that memory

As you can see, fiddling with the new operator would require you to call
constructors by hand, which is impossible.

The first point was a call to operator new. That operator you can
overload as any other operator. Its function is to provide a pointer to
enough memory for the object to construct itself; this is a malloc-like
function and actually, the default implementation is usually written in
terms of malloc().
But Herbal Sutter
:)
mentioned in his greate book 'exceptional c++' about free
storage
and heap..
He said they are differenct and we need to know the differences..
That was a theoritical question.
But I'm still confused about they are different..
I've thought actually both new and malloc use heap..


The standard doesn't require them to do so, but that's what happens in
real life.

Calling malloc() returns a pointer to a block of memory on the heap
which has the given size :

malloc(sizeof(M yClass));

returns a pointer to a block of sizeof(MyClass) bytes. That's raw memory.

new MyClass;

return a pointer to a block of sizeof(MyClass) bytes on which the
constructor was called. So that block is not raw memory: it's a valid
object. That was done in two steps, the steps described above.

The conclusion is : malloc() only allocates raw memory and new allocates
raw memory on which the constructor is called. Something like

// what the new operator does behind your back:

// allocate raw memory
MyClass *p = reinterpret_cas t<MyClass*>(mal loc(sizeof(MyCl ass)));

// call constructor
p->MyClass();

Of course that code is invalid since calling constructors is illegal,
but that's what the compiler is doing behind your back. Since we're in
C++, the malloc() call is replaced by a call to operator new :

// allocate raw memory
MyClass *p = reinterpret_cas t<MyClass*>(ope rator new(sizeof(MyCl ass)));

// call constructor
p->MyClass();

And usually, as I said, operator new is implemented in terms of malloc :

void *operator new(std::size_t size)
{
return malloc(size);
}

though you could override it to call some application-specific functions
(such as memory pool functions).

Jonathan
Jul 22 '05 #7
I also have a question here regarding the constructor and destructor calls.
Since malloc and free are C functions, they know nothing about constructor
or destructor calls.
However, in your example, operator 'new' is nothing but a malloc call with a
new look. How would the compiler figure out which constructor to call? If
at all?
In fact, Scott Meyers says in 'Effective C++' that you should never ever use
malloc and free for exactly that reason.

Can you clarify that?

- Matthias

Larry Brasfield wrote:
The constructor is called in the same way as is usual, after
a location for the object has been determined or arranged.
Why is it called? To convert raw memory into a proper
instance of the class. This is the constructor's role, to be
distinguished from somehow obtaining raw memory.


Jul 22 '05 #8
BekTek wrote:
Hi..
I'm so sorry about that I've postes so many questions recently.. :)

I'm still confused about the differences between malloc and operator new..
I know that when we work with class object and use operator new/delete, the
ctor and dtor
get called as expected, but malloc and free do not..

But Herbal Sutter mentioned in his greate book 'exceptional c++' about free
storage
and heap..
He said they are differenct and we need to know the differences..

But I'm still confused about they are different..
I've thought actually both new and malloc use heap..

can some clearify me?

The malloc()/free() family should be avoided in C++, because when used
the constructors and destructors are not called. They work for POD types
only.
On the other hand the operator new/delete family work for all types, so
you had better use them, and NOT the malloc()/free() family.
Free storage and "heap" are the same thing.


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #9
Jonathan Mcdougall wrote:
There is a difference between operator new and the new operator: the
latter calls the former.

What is this? There is no guarantee for such a thing. Do you have TC++PL 3?


--
Ioannis Vranos

http://www23.brinkster.com/noicys
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
2056
by: Bern | last post by:
what are all the diferences between the two?
16
6781
by: RS | last post by:
Hi, What is the difference between new() and malloc()? RS
6
2430
by: Vinu | last post by:
Hi, I am maintaining a C++ project which is a server which continuously receives requeste from clients. I have noticed that we overload the new operator and in it then call malloc to allocate memory. Specifically the code is something like this.
34
6418
by: Richard Hunt | last post by:
I'm sorry for asking such a silly question, but I can't quite get my head around malloc. Using gcc I have always programmed in a lax C/C++ hybrid (which I suppose is actually c++). But I have started messing around in Plan 9, and that sort of thing is totally no go there :). Is this correct to allocate memory for my struct? It works on my...
15
6977
by: Paul Morrison | last post by:
Hi all, I need to come up with some differences between arrays in Java and C, I have searched Google and so far all I have found is the following: Arrays in Java are reference types with automatic allocation of memory. In C, arrays are groups of variables of the same type in adjacent memory. Allocation for dynamic arrays is handled by the...
11
12463
by: blangela | last post by:
I am teaching a C programming course to C++ programmers and want to come up with list of _KEY_ differences between the two languages. Below is a list I have come up with so far. Have I missed any? Key Differences between ANSI C and C++ 1. C is a procedural programming language (where as C++ is an Object Oriented Programming language). ...
71
19061
by: desktop | last post by:
I have read in Bjarne Stroustrup that using malloc and free should be avoided in C++ because they deal with uninitialized memory and one should instead use new and delete. But why is that a problem? I cannot see why using malloc instead of new does not give the same result.
23
2706
by: raphfrk | last post by:
I am having an issue with malloc and gcc. Is there something wrong with my code or is this a compiler bug ? I am running this program: #include <stdio.h> #include <stdlib.h> typedef struct pxl { double lon, lat;
0
7918
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7843
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8340
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
8220
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6621
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5392
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3840
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3875
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1185
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.