473,785 Members | 2,831 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

whats the advantageof malloc over new in c++.

whats the beauty of "malloc" over "new" why its helpful for
programmer.for its own memory area.??
Aug 19 '08
26 3847
On Aug 21, 9:13 pm, ytrem...@nyx.ny x.net (Yannick Tremblay) wrote:
In article <bd7a4e3f-0781-4441-af02-f3976675e...@x1 6g2000prn.googl egroups.com>,

<tony_in_da...@ yahoo.co.ukwrot e:
On Aug 21, 1:51 am, "Bo Persson" <b...@gmb.dkwro te:
tony_in_da...@y ahoo.co.uk wrote:
Anyway, only the additional elements need then be manually
constructed with placement new... and this doesn't necessarily need
to be done using a default constructor before the meaningful values
are available which can be an advantage... so at least this
two-step process can work for some things with constructors.
But realloc() takes a void* pointer to the memory block, so it doesn't
know what kind of objects it contains.
Perhaps I didn't explain that well... sorry... off-the-top-of-my head
coding here:
if (X* p = (X*)realloc(old _p, sizeof(X) * new_capacity))
for (int n = old_size; n < new_capacity; ++n)
new(p[n]) X(fn(n)); // meaningful construction...

Hmm, tell me what happens in the code above if realloc unfortunately
fail to be able to grow in place and need to malloc new memory at a
different place?

Guess if X is memcpy-able you'll survive but if not, you are dead.
Agreed - discussed earlier in another of my posts to this thread.
What advantage does this has over (apart from being more bug prone):

std:vector<Xv;
// v.reserve(somen umber); //optional
// ...
for(size_t n = v.size(); v < nerw_capacity ; ++v)
v.append(X(f(n) ));

Yan
The advantage (strange that you list error proneness as an advantage)
that I was discussed was that you're making a more explicit request
that the vector not be moved unless necessary.

You seem to be misunderstandin g my posts... we're not recommending
these usages, but explaining differences and why sometimes some
vaguely credible excuse/argument for using malloc/realloc/free exists.

Tony
Aug 22 '08 #21
In article <05************ *************** *******@79g2000 hsk.googlegroup s.com>,
<to***********@ yahoo.co.ukwrot e:
>On Aug 21, 9:13 pm, ytrem...@nyx.ny x.net (Yannick Tremblay) wrote:
>In article
<bd7a4e3f-0781-4441-af02-f3976675e...@x1 6g2000prn.googl egroups.com>,
>>
<tony_in_da...@ yahoo.co.ukwrot e:
>if (X* p = (X*)realloc(old _p, sizeof(X) * new_capacity))
for (int n = old_size; n < new_capacity; ++n)
new(p[n]) X(fn(n)); // meaningful construction...

Hmm, tell me what happens in the code above if realloc unfortunately
fail to be able to grow in place and need to malloc new memory at a
different place?

Guess if X is memcpy-able you'll survive but if not, you are dead.

Agreed - discussed earlier in another of my posts to this thread.
>What advantage does this has over (apart from being more bug prone):

std:vector<X v;
// v.reserve(somen umber); //optional
// ...
for(size_t n = v.size(); v < nerw_capacity ; ++v)
v.append(X(f(n) ));

Yan

The advantage (strange that you list error proneness as an advantage)
Sorry, a smiley should have been added. That was an attempt at irony.
>that I was discussed was that you're making a more explicit request
that the vector not be moved unless necessary.
(which is exactly what std::vector does)
The problem is that you do not know in advance if the realloc can
grow the buffer or if it will need to malloc and copy. Either can
happen. This makes the construct pointless. Worse, it gives the
illusion to the poor programmer that the memory will not be moved and
it hides bugs.
>You seem to be misunderstandin g my posts... we're not recommending
these usages, but explaining differences and why sometimes some
vaguely credible excuse/argument for using malloc/realloc/free exists.
But my point was this is not even a vaguely credible excuse. It is
simply WRONG. std::vector will do the right thing. It will probably
internally try to grow its buffer and not move it unless necessary.
If you use reserve, it will not need to move/copy. If you didn't or
grow beyond the originally reserved size, if it can grow its buffer,
its performance characteristics will be similar to the use of realloc,
if it can't grow in place, it will copy correctly.

It is not a question of not recommending using realloc with objects.
It should be actively recommended against.

Essentially, to go back to the subject of this thread:

If you write C++ use new.
(you can stop reading here)

There are very few reasons to use malloc in C++. Most of the excuses
given by poor programmers to use malloc are incorrect overlooking a
few issues.

If you really really think you must use malloc, only do it with basic
POD-types. The most valid reason I can think of is that you must
allocate memory that will be passed to _and_ freed by a C module. If
that's the case,then it must be POD anyway.

Although it is possible to malloc and use placement new, don't do it.
It's not worth it. You are likely lying to yourself about the
benefits, you are likely to fall into a trap, you would be writing
unmaintainable software.

If you still really really think that you must use malloc for C++
objects, think about it again, find a better C++ programmer than you
and show him your design and proposed code and ask him to help you
find a better solution. If the guru can't find a better way, make sure
he is really a C++ guru and a good software developper. If that's the
case, then maybe, just maybe you found the exception that confirms the
rule.

Yannick
P.S.:
sorry for the preaching but I've had the unfortunate experience of
working with bad programmers in my life. Bad C programmers having
moved to C++ insisting on using malloc because it's what they've
always used. Doing awful premature optimisation without profiling.
Wanting to use malloc/realloc because "C++ is slow and does things
under the hood without telling you" without having profiled nor
bothered looking at std::vector implementation.

Aug 22 '08 #22
On Aug 21, 2:46*am, Ian Collins <ian-n...@hotmail.co mwrote:
Chris Becke wrote:
A clear disadvantage. *:-)
You have to check the result manually instead.
predictable program flow is a disadvantage? Not even google likes c++ exceptions.

Their loss.

--
Ian Collins.
Ian

To make the discussion concrete, it might be interesting to address
the Cons mentioned at this link:
http://google-styleguide.googlecode....ons#Exceptions

It does look like Google is simply talking about difficulty of
introducing exceptions in an existing codebase and they do agree that
their benefits far outweigh the costs.

Aug 22 '08 #23
Dilip wrote:
On Aug 21, 2:46 am, Ian Collins <ian-n...@hotmail.co mwrote:
>Chris Becke wrote:
>>>A clear disadvantage. :-)
You have to check the result manually instead.
predictable program flow is a disadvantage? Not even google likes c++ exceptions.
Their loss.

Ian

To make the discussion concrete, it might be interesting to address
the Cons mentioned at this link:
http://google-styleguide.googlecode....ons#Exceptions

It does look like Google is simply talking about difficulty of
introducing exceptions in an existing codebase and they do agree that
their benefits far outweigh the costs.
In that context their rule does make sense.

--
Ian Collins.
Aug 22 '08 #24
On Aug 22, 6:36*pm, ytrem...@nyx.ny x.net (Yannick Tremblay) wrote:
In article <05c12633-ec68-489a-afcf-25beadbb8...@79 g2000hsk.google groups.com>,
*<tony_in_da... @yahoo.co.ukwro te:
if (X* p = (X*)realloc(old _p, sizeof(X) * new_capacity))
* *for (int n = old_size; n < new_capacity; ++n)
* * * *new(p[n]) X(fn(n)); // meaningful construction...
What advantage does this has over (apart from being more bug prone):
std:vector<Xv;
// v.reserve(somen umber); //optional
// ...
for(size_t n = v.size(); v < nerw_capacity ; ++v)
* * v.append(X(f(n) ));
[realloc advantage] you're making a more explicit request
that the vector not be moved unless necessary.

(which is exactly what std::vector does)
The problem is that you do not know in advance if the realloc can
grow the buffer or if it will need to malloc and copy. *Either can
happen. *This makes the construct pointless. *Worse, *it gives the
illusion to the poor programmer that the memory will not be moved and
it hides bugs. *
I think this is the second time in this thread that the "can't be sure
= useless" argument has been put. It's blatantly absurd: for example,
is a hash_map useless because it might have a collision? Laws of
averages are relevant.

Re may-or-may-not introducing two code paths to test / hides bugs:
agreed - using malloc/realloc/free is definitely much more fraught
with risks than new/delete. That's not really relevant either, as I'm
saying realloc has one potential advantage - you can be sure if will
realloc in-place if possible - not defending the overall balance of
pros and cons.
You seem to be misunderstandin g my posts... we're not recommending
these usages, but explaining differences and why sometimes some
vaguely credible excuse/argument for using malloc/realloc/free exists.

But my point was this is not even a vaguely credible excuse. *It is
simply WRONG. *std::vector will do the right thing. *It will probably
internally try to grow its buffer and not move it unless necessary.
"Proabably" ? What gives you this idea? The old SGI STL provided a
hint to the allocator which could be used for this, but to the best of
my knowledge this is not common practice in current STL
implementations , it's not available in the GCC headers shipped with
the current Dev-C++ (sorry / no real machine to check handy), and the
Oct '97 draft Standard section 20.1.5.2 Table 6 makes it clear that
there's no expectation of any support for realloc or the SGI-style
hint.
If you use reserve, it will not need to move/copy.
If you didn't or
grow beyond the originally reserved size, if it can grow its buffer,
its performance characteristics will be similar to the use of realloc,
if it can't grow in place, it will copy correctly.
Yes, but often not possible (e.g. when appending elements as they
arrive from an IPC mechanism, or are entered by a user).
It is not a question of not recommending using realloc with objects.
It should be actively recommended against. *
Yes, I believe I've done that already "Still, the short story is don't
use malloc/realloc and free unless you find a reason to have to.".
That doesn't mean that the pros/cons can't be objectively enumerated
and weighed.
Essentially, to go back to the subject of this thread:

If you write C++ use new. *
(you can stop reading here)
Pretty much right. Anyone experienced enough to understand that they
really must use new doesn't need to read this thread anyway....
sorry for the preaching but I've had the unfortunate experience of
working with bad programmers in my life. *Bad C programmers having
moved to C++ insisting on using malloc because it's what they've
always used. *Doing awful premature optimisation without profiling.
Wanting to use malloc/realloc because "C++ is slow and does things
under the hood without telling you" without having profiled nor
bothered looking at std::vector implementation. *
Yes, part of being a programmer... quite understand.

Cheers,

Tony
Aug 23 '08 #25
In article <3b************ *************** *******@b2g2000 prf.googlegroup s.com>,
<to***********@ yahoo.co.ukwrot e:
>On Aug 22, 6:36*pm, ytrem...@nyx.ny x.net (Yannick Tremblay) wrote:
>In article <05c12633-ec68-489a-afcf-25beadbb8...@79 g2000hsk.google groups.com>,
>*<tony_in_da.. .@yahoo.co.ukwr ote:
if (X* p = (X*)realloc(old _p, sizeof(X) * new_capacity))
* *for (int n = old_size; n < new_capacity; ++n)
* * * *new(p[n]) X(fn(n)); // meaningful construction...
>What advantage does this has over (apart from being more bug prone):
>std:vector<X v;
// v.reserve(somen umber); //optional
// ...
for(size_t n = v.size(); v < nerw_capacity ; ++v)
* * v.append(X(f(n) ));
[should have been push_back(), sorry]
>[realloc advantage] you're making a more explicit request
that the vector not be moved unless necessary.

(which is exactly what std::vector does)
The problem is that you do not know in advance if the realloc can
grow the buffer or if it will need to malloc and copy. *Either can
happen. *This makes the construct pointless. *Worse, *it gives the
illusion to the poor programmer that the memory will not be moved and
it hides bugs. *

I think this is the second time in this thread that the "can't be sure
= useless" argument has been put. It's blatantly absurd: for example,
is a hash_map useless because it might have a collision? Laws of
averages are relevant.
There's a huge difference between hash_map collisions and failure of
realloc to grow in place in the code above: a hash_map is designed to
handle hash collision, a collision simply result in slightly slower
access time. In the sample code above, realloc deciding that it needs
to move everything elsewhere and memcpy results in a bug! That is not
comparable. Law of average should not be used if it mean that "most
of the time my program will work but once in a while it will crash"
rather than "most of the time my program will be fast but once in a
while it will get a bit slower".
>Re may-or-may-not introducing two code paths to test / hides bugs:
agreed - using malloc/realloc/free is definitely much more fraught
with risks than new/delete. That's not really relevant either, as I'm
saying realloc has one potential advantage - you can be sure if will
realloc in-place if possible - not defending the overall balance of
pros and cons.
You can be sure that if it is possible it will realoc in place
but you can't know "if it is possible". So essentially, you know
nothing and you are sure of nothing.
>But my point was this is not even a vaguely credible excuse. *It is
simply WRONG. *std::vector will do the right thing. *It will probably
internally try to grow its buffer and not move it unless necessary.

"Proabably" ? What gives you this idea? The old SGI STL provided a
hint to the allocator which could be used for this, but to the best of
my knowledge this is not common practice in current STL
implementation s, it's not available in the GCC headers shipped with
the current Dev-C++ (sorry / no real machine to check handy), and the
Oct '97 draft Standard section 20.1.5.2 Table 6 makes it clear that
there's no expectation of any support for realloc or the SGI-style
hint.
Sorry, you are right, my implementation appears to move the buffer
(and copy everything) every time vector.capacity () changes.

So I am left only with that vector will work all the time and if you
can use reserve() it will be as performant as realloc.
>If you use reserve, it will not need to move/copy.

Yes, but often not possible (e.g. when appending elements as they
arrive from an IPC mechanism, or are entered by a user).
Correct me if I am wrong but my understanding of realloc is that it is
most likely to be able to grow in place if there are few allocations
happening e.g. if you are in a loop and the only dynamic memory
allocation that happens is the realloc, it _might_ well be bounded by
unused space and will be able to grow in-place. However, if there are
other mallocs happening between reallocs, these are likely to be
placed right after the realloc buffer and stop it being able to grow
in place.

My point is that in a complex system, you might not be able to use
reserve() correctly but also realloc() is likely not to grow
in-place. In a simpler system where few things happen and realloc has
a good chance to grow-in-place, you might also be able to use
reserve() in a useful way. Obviously there are exceptions.
>Yes, I believe I've done that already "Still, the short story is don't
use malloc/realloc and free unless you find a reason to have to.".
That doesn't mean that the pros/cons can't be objectively enumerated
and weighed.
Yes, I understand that you understand. :-) I am mostly arguing that
what at first sight might appear like a worthy consideration for using
realloc in C++ is quite possibly not and one should look again :-)

Yannick
Aug 26 '08 #26
On Aug 26, 8:07 pm, ytrem...@nyx.ny x.net (Yannick Tremblay) wrote:
There's a huge difference between hash_map collisions
and failure of realloc to grow in place in the code above:
a hash_map is designed to handle hash collision, a collision
simply result in slightly slower access time. In the sample
code above, realloc deciding that it needs to move everything
elsewhere and memcpy results in a bug! That is not
comparable. Law of average should not be used if it mean
that "most of the time my program will work but once in a
while it will crash" rather than "most of the time my
program will be fast but once in a while it will get a bit
slower".
The code to which you refer is safe for any data which can be safely
and silently relocated. Within those boundaries, use of realloc is
indeed a simple sometimes-fast / sometimes-slow situation.
You can be sure that if it is possible it will realoc in place
but you can't know "if it is possible". So essentially, you
know nothing and you are sure of nothing.
What kind of FUD argument is this? You know realloc has three
possible outcomes - failure to resize, inplace resize, or some manner
of memcopy/move+resize. This isn't impractical - one or two C
programmers have actually written reliable systems handling these
branches. I met one once. His name was Bob. He looked very sad.
But my point was this is not even a vaguely credible excuse. It is
simply WRONG. std::vector will do the right thing. It will probably
internally try to grow its buffer and not move it unless necessary.
The old SGI STL provided a hint to the allocator which
could be used for this, but to the best of
my knowledge this is not common practice in current STL
implementations , it's not available in the GCC headers
shipped with the current Dev-C++ [...], and the
Oct '97 draft Standard section 20.1.5.2 Table 6 makes
it clear that there's no expectation of any support for
realloc or the SGI-style hint.

Sorry, you are right, my implementation appears to move
the buffer (and copy everything) every time
vector.capacity () changes.

So I am left only with that vector will work all the time
and if you can use reserve() it will be as performant
as realloc.
Two very important considerations, but not the basis for a "never
never never use realloc" recommendation.
If you use reserve, it will not need to move/copy.
Yes, but often not possible (e.g. when appending elements as they
arrive from an IPC mechanism, or are entered by a user).

Correct me if I am wrong but my understanding of realloc
is that it is most likely to be able to grow in place if
there are few allocations happening e.g. if you are in a
loop and the only dynamic memory allocation that happens
is the realloc, it _might_ well be bounded by
unused space and will be able to grow in-place. However,
if there are other mallocs happening between reallocs,
these are likely to be placed right after the realloc
buffer and stop it being able to grow in place.

My point is that in a complex system, you might not be
able to use reserve() correctly but also realloc() is
likely not to grow in-place. In a simpler system where
few things happen and realloc has a good chance to
grow-in-place, you might also be able to use
reserve() in a useful way. Obviously there are
exceptions.
Memory allocation schemes are many and varied, so we can't draw firm
conclusions. Still, I know it's not unusual for them to use separate
pools for different sized requests, rather than allowing any small
malloc request coming along to pack right in behind the last request.
I vaguely remember having heard of schemes deliberately scattering or
otherwise targetting allocations to maximise the chance of in-place
realloc.

Doing a very quick Google, I found:
- Paul Hsieh's "bstrlib.c" assumes 1 in 8 reallocs are in-place
(didn't find any justification, sounds pessimistic to me but I didn't
look at the string operation context)
- a similar discussion (with some "big-name" contributors ;-)) at
http://www.cpptalk.net/1-vt23200.htm...er=asc&start=0
Yes, I believe I've done that already "Still, the short
story is don't use malloc/realloc and free unless you
find a reason to have to.".
That doesn't mean that the pros/cons can't be
objectively enumerated and weighed.

Yes, I understand that you understand. :-) I am mostly
arguing that what at first sight might appear like a
worthy consideration for using realloc in C++ is quite
possibly not and one should look again :-)

Yannick
Quite so - it'd need to be extreme circumstances before I'd even
consider it seriously....

Cheers,

Tony
Aug 27 '08 #27

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

Similar topics

19
683
by: john smith | last post by:
Can someone please explain to me what is happening when I do a malloc(0). This is what I did. int* p = (int*)malloc(0); Then I printed the value of p and of course it was non-null. But has it allocated memory or what?
231
23247
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be correct form?
7
2216
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ http://www.eskimo.com/~scs/C-faq/faq.html but it doesn't seem to answer my questions... So, I've made an example behind, with some included questions...
5
2835
by: kernel.lover | last post by:
hello, I want to know if a fuction say malloc is declared as void *malloc() then whats the significance of void here. Does void * is used when function has the flexibility to return any type of value by casting that functions with appropriate data type?
4
2282
by: lothar.behrens | last post by:
Hi, my own stream implementation writes correctly, but it does not read all back. Why ? Thanks, Lothar Here is the output: 'Testdata1: ', 0
15
2591
by: Martin Jørgensen | last post by:
Hi, I have a (bigger) program with about 15-30 malloc's in it (too big to post it here)... The last thing I tried today was to add yet another malloc **two_dimensional_data. But I found out that malloc always returned null at this moment and the program exited (even though if I malloc'ed only 20 bytes or something)... Then I googled for this problem and found something about a memory pool??? Is that standard C? I didn't understand it,...
8
2237
by: Martin Jørgensen | last post by:
Hi, "C primer plus" p.382: Suppose we have this declaration: int (*pa); int ar1; int ar2; int **p2;
68
15715
by: James Dow Allen | last post by:
The gcc compiler treats malloc() specially! I have no particular question, but it might be fun to hear from anyone who knows about gcc's special behavior. Some may find this post interesting; some may find it off-topic or confusing. Disclaimers at end. The code samples are intended to be nearly minimal demonstrations. They are *not* related to any actual application code.
71
19135
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.
0
9645
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10324
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10090
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8971
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6739
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5380
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.