473,739 Members | 9,109 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

difference in implementation between operator new and new []

Hi,
I was looking at the implementation of operator new and operator
new[] in gcc source code and found that the implementation is exactly
the same. The only difference is that the size_t argument passed to
the operators is calculated correctly during runtime and passed in.
Inside the implementation both operators (new and new[]) do a simple
malloc(). Ditto for operator delete/delete[]. I have two questions:
1) Who passes in the size_t argument at runtime?
2) If the operator implementations are virtually the same (at least
for gcc), can we assume that mismatched new[]/delete and new/delete[]
calls will not result in any problem? I ask this because I was doing
an exercise of finding memory leaks inside some C++ code. When I
executed the code with Valgrind, I got a bunch of mismatched new[]/
delete errors. However there were no reported memory leaks as such.
However I assumed that doing a new[] and then a delete would most
probably leak memory because delete would probably delete only the
first object of the array (since the implementation of operator delete
will not know about the array size). So I wrote a small C++ program
where I do a lot of new[]'s and delete's on my Linux box and then
monitored the memory footprint using the top command. However contrary
to my expectations, there were no memory leaks. That is when I started
looking into the implementation of operator new/new[] and operator
delete/delete[] in gcc source code and found out that there is no
difference in the internal implementation of the scalar and the
corresponding vector operator.
Sep 24 '08 #1
3 3518
On Sep 24, 1:15 pm, "C++Liliput " <aveekmi...@gma il.comwrote:
Hi,
I was looking at the implementation of operator new and operator
new[] in gcc source code and found that the implementation is exactly
the same. The only difference is that the size_t argument passed to
the operators is calculated correctly during runtime and passed in.
Inside the implementation both operators (new and new[]) do a simple
malloc(). Ditto for operator delete/delete[]. I have two questions:
1) Who passes in the size_t argument at runtime?
2) If the operator implementations are virtually the same (at least
for gcc), can we assume that mismatched new[]/delete and new/delete[]
calls will not result in any problem? I ask this because I was doing
an exercise of finding memory leaks inside some C++ code. When I
executed the code with Valgrind, I got a bunch of mismatched new[]/
delete errors. However there were no reported memory leaks as such.
However I assumed that doing a new[] and then a delete would most
probably leak memory because delete would probably delete only the
first object of the array (since the implementation of operator delete
will not know about the array size). So I wrote a small C++ program
where I do a lot of new[]'s and delete's on my Linux box and then
monitored the memory footprint using the top command. However contrary
to my expectations, there were no memory leaks. That is when I started
looking into the implementation of operator new/new[] and operator
delete/delete[] in gcc source code and found out that there is no
difference in the internal implementation of the scalar and the
corresponding vector operator.
If new/delete and new[]/delete[] happen to be implemented on top of
malloc()/free() in your implementation, and given that new[] must
allocate contiguous memory in one block and that free() doesn't
require the size_t as a parameter (the memory subsystem remembers the
size anyway), this all hangs together. That's why it - observably -
"works". What doesn't hang together is the construction and
destruction of your elements: new[] and delete[] ensure each
individual object has it's destructor or destructor called
(respectively). Not using the correct operation doesn't give the
compiler the opportunity to ensure this is done correctly. Even if
you're working with POD data that ostensibly needs no construction/
destruction, what you're doing is undefined by the Standard, and even
a future revision of your compiler (let alone a different compiler/
machine/OS) might not layer over malloc()/free() so transparently.
You're asking for a crash.

Cheers, Tony
Sep 24 '08 #2
C++Liliput wrote:
Hi,
I was looking at the implementation of operator new and operator
new[] in gcc source code and found that the implementation is exactly
the same. The only difference is that the size_t argument passed to
the operators is calculated correctly during runtime and passed in.
Inside the implementation both operators (new and new[]) do a simple
malloc(). Ditto for operator delete/delete[]. I have two questions:
1) Who passes in the size_t argument at runtime?
It's computed magically by the implementation. See the example [5.3.4/12]:

? new T results in a call of operator new(sizeof(T)),
? ...
? new T[5] results in a call of operator new[](sizeof(T)*5+x) , and
? ...

2) If the operator implementations are virtually the same (at least
for gcc), can we assume that mismatched new[]/delete and new/delete[]
calls will not result in any problem?
a) You are relying on the behavior of a particular implementation and
b) NO, not even with g++. Compile with g++ and run under valgrind:

struct X {

char * buffer;

X ( void ) {
buffer = new char;
}

~X ( void ) {
delete buffer;
}

};

int main ( void ) {
X* xp = new X [16];
delete xp; // mismatch !
}
Best

Kai-Uwe Bux
Sep 24 '08 #3
C++Liliput wrote:
I was looking at the implementation of operator new and operator
new[] in gcc source code and found that the implementation is exactly
the same. The only difference is that the size_t argument passed to
the operators is calculated correctly during runtime and passed in.
Inside the implementation both operators (new and new[]) do a simple
malloc(). Ditto for operator delete/delete[].
OK.
I have two questions:
1) Who passes in the size_t argument at runtime?
When the compiler generates the code for new-expression ('new' or
'new[]' form), it also generates the code that will calculate the
run-time size and pass it to 'operator new'/'operator new[]' functions.

I hope you know that new-expression that you use in your code is not
even remotely the same as 'operator new' function. The call to the
'operator new' function is nothing but just a small part of what
new-expression actually does. The same applies to delete-expression and
'operator delete' function.
2) If the operator implementations are virtually the same (at least
for gcc), can we assume that mismatched new[]/delete and new/delete[]
calls will not result in any problem?
No. Why? In this question you must be referring to mismatched
new-expression and delete-expression formats. Once again, the actual
call to the appropriate 'operator new' function is just a small part of
what new-expression translates to. The same applies to
delete-expression. If you really want to know whether they are
"compatible " in some particular implementation, you need to compare the
entire code that is generated for these expressions, not just the code
for 'operator new'/'operator delete'. The code for the expression is
normally generated intrinsically, i.e. you won't find any "source code"
for it in the library. You'll have analyze the assembly code, and do it
for every possible combination of types, compiler settings, etc. This is
a useless waste of time, if you ask me.
I ask this because I was doing
an exercise of finding memory leaks inside some C++ code. When I
executed the code with Valgrind, I got a bunch of mismatched new[]/
delete errors. However there were no reported memory leaks as such.
Memory leaks? What made you to conclude that there must be memory leaks
specifically? Mismatched new/delete result in undefined behavior.
There's no way to predict how it will manifest itself. The belief in
that it should specifically cause "memory leaks" is an urban legend. I
don't know where it comes from.

--
Best regards,
Andrey Tarasevich
Sep 24 '08 #4

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

Similar topics

2
3665
by: diadia | last post by:
string s = "hello"; const char *p = s.begin(); cout << p << endl; // print hello s = ""; char *p2= s.begin(); cout << p2 << endl; // print hello why?????
18
7829
by: Metro12 | last post by:
In the <basic_string.h>, I find the implementation of these two functions. But I can't understand the difference between them. Please give me some help! //basic_string::c_str() const _CharT* c_str() const { // MT: This assumes concurrent writes are OK. size_type __n = this->size(); traits_type::assign(_M_data(), _Rep::_S_terminal);
7
2712
by: Dev | last post by:
Hello, In the following class definition, the ZString destructor is invoked two times. This crashes the code. class ZString { public: ZString(char* p)
83
15599
by: rahul8143 | last post by:
hello, what is difference between sizeof("abcd") and strlen("abcd")? why both functions gives different output when applied to same string "abcd". I tried following example for that. #include <stdio.h> #include <string.h> void main() { char *str1="abcd";
13
1602
by: Ankit | last post by:
Hello, I have an old VC++ project code base which I am trying to build and use. This uses an ostream object. Now in my project, I have overloaded the leftshift operator ( << ), basically being used to "put" data to the stream object. However, while I run the app, it does not call the correct implementation of the operator. For example, say I have following piece of code: ostream o;
47
1917
by: mwql | last post by:
Hey guys, this maybe a stupid question, but I can't seem to find the result anywhere online. When is the right time to use 'is' and when should we use '=='? Thanks alot~
6
4927
by: mthread | last post by:
Hi, I am learning C++ and I have been told that an object can be created either by using calloc or new. If it is true, can some one tell me what is the difference b/w using these two function calls.
3
1447
by: stef | last post by:
Hello, Could you tell me the difference between char &operator(int idx) { return tab; } and
350
11813
by: Lloyd Bonafide | last post by:
I followed a link to James Kanze's web site in another thread and was surprised to read this comment by a link to a GC: "I can't imagine writing C++ without it" How many of you c.l.c++'ers use one, and in what percentage of your projects is one used? I have never used one in personal or professional C++ programming. Am I a holdover to days gone by?
0
8969
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
8792
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9479
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...
1
9266
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
9209
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8215
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
6054
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();...
1
3280
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2193
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.