473,666 Members | 2,565 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using delete instead of delete[] for 1 integer

If I allocate memory like this

int *ptr = new int[1];

Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.

Dec 24 '06 #1
9 2909
"Money" <sp*********@gm ail.comwrote in message
news:11******** **************@ a3g2000cwd.goog legroups.com...
If I allocate memory like this

int *ptr = new int[1];

Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.
Undefined. It may work, it may not. It all depends on how the compiler/OS
is handling new/new[] and delete/delete[]. It may even appear to work and
have side effects you're not aware of. In other words, I wouldn't do it.
Dec 24 '06 #2

Jim Langston wrote:
"Money" <sp*********@gm ail.comwrote in message
news:11******** **************@ a3g2000cwd.goog legroups.com...
If I allocate memory like this

int *ptr = new int[1];

Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.

Undefined. It may work, it may not. It all depends on how the compiler/OS
is handling new/new[] and delete/delete[]. It may even appear to work and
have side effects you're not aware of. In other words, I wouldn't do it.
But why would it be undefined?
delete ptr; will release memory for atleast 1 integer and that's what I
want.

Dec 24 '06 #3

Money wrote:
Jim Langston wrote:
"Money" <sp*********@gm ail.comwrote in message
news:11******** **************@ a3g2000cwd.goog legroups.com...
If I allocate memory like this
>
int *ptr = new int[1];
>
Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.
Undefined. It may work, it may not. It all depends on how the compiler/OS
is handling new/new[] and delete/delete[]. It may even appear to work and
have side effects you're not aware of. In other words, I wouldn't do it.

But why would it be undefined?
delete ptr; will release memory for atleast 1 integer and that's what I
want.
One reason is that arrays may be allocated differently than objects.
For example, the runtime may store information about an allocation
before the start of the block - and conceivably the format of this
information could differ for an array allocation than an allocation of
a non-array, single object. (Note that the size of the array makes no
difference to the format selected, all arrays of any size are treated
alike).

So if the form of (delete or delete[]) when deleting an array or object
does not match the form of the new operator (new or new[]) that was
used to allocate it, then runtime would interpret the block's stored
information incorrectly - by assuming the data is stored in a format
that is not the same as the format it was stored in - and whatever
happens after the point is uncertain (that is, undefined), and is
unlikely to be good.

Greg

Dec 24 '06 #4
Money wrote:
Jim Langston wrote:
>"Money" <sp*********@gm ail.comwrote in message
news:11******* *************** @a3g2000cwd.goo glegroups.com.. .
>>If I allocate memory like this

int *ptr = new int[1];

Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.

Undefined. It may work, it may not. It all depends on how the
compiler/OS is handling new/new[] and delete/delete[]. It may
even appear to work and have side effects you're not aware of. In
other words, I wouldn't do it.

But why would it be undefined?
delete ptr; will release memory for atleast 1 integer and that's
what I want.

Because the standard says so. :-)

The compiler is allowed to make it NOT work if it feels like. Or some other
compiler you try, or the next release.

Just don't do it!
Why would you use new to allocate a single int anyway?
Bo Persson
Dec 24 '06 #5


On Dec 24, 2:04 pm, "Money" <spicymon...@gm ail.comwrote:
Jim Langston wrote:
"Money" <spicymon...@gm ail.comwrote in message
news:11******** **************@ a3g2000cwd.goog legroups.com...
If I allocate memory like this
int *ptr = new int[1];
Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.
Undefined. It may work, it may not. It all depends on how the compiler/OS
is handling new/new[] and delete/delete[]. It may even appear to work and
have side effects you're not aware of. In other words, I wouldn't do it.But why would it be undefined?
delete ptr; will release memory for atleast 1 integer and that's what I
want.
C++,s new/new[] and delete/delete[] are overloadable operators they
might be instructed to place arrays on different heap than single
objects.So your program
might simplly crash.You are programing with high risk.

Dec 24 '06 #6

Money wrote:
If I allocate memory like this

int *ptr = new int[1];

Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.
It may or may not work, depending on the implementation, and even the
version. But, it would not be portable code. You should ALWAYS use
delete [] to delete something that was allocated with new [].

Dec 24 '06 #7
Money wrote:
If I allocate memory like this

int *ptr = new int[1];

Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.
For Plain Old Datatype (POD) like an int, it likely not to
matter. delete[] also destructs each of the elements of the
array. If you use 'delete', you'll bypass destructing the
elements of the array.

Also, naked pointers are obscene. Never declare a unwrapped int
*. Wrap it with a boost:scoped_ar ray<or boost:shared_ar ray<>.
This way you won't need to worry about whether to call
delete[] or delete. Make the object take care of itself.

/Glen Dayton
Dec 24 '06 #8

Money wrote:
If I allocate memory like this

int *ptr = new int[1];

Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.
You can't because its not guaranteed. Although on most compilers the
above might work you still are left with the uncertainty that it may
fail. That is, an implementation of a primitive array is not required
to make the above delete correctly (what the specific details of such
an implementation might be doesn't matter). You've got other things to
worry about.

Whats relevent to you is the fact that if one day somebody decides that
they need new int[2] instead of new int[1], your deletion should still
work. And it will if you follow the standard, delete[] ptr is
guarenteed.

Dec 24 '06 #9
Glen Dayton <RE**********@i eee.orgwrote in news:FnAjh.44$j i1.9
@newssvr12.news .prodigy.net:
Money wrote:
>If I allocate memory like this

int *ptr = new int[1];

Can I apply delete ptr; instead of delete[] ptr; since I am only
allocating memory for 1 integer.

For Plain Old Datatype (POD) like an int, it likely not to
matter. delete[] also destructs each of the elements of the
array. If you use 'delete', you'll bypass destructing the
elements of the array.
Not necessarily true. An array may be allocated differently than a
single object (and we're not talking about construction/destruction).

I could see one potential implementation as follows:

- When allocating memory for a single object, allocate sizeof(int) +
sizeof(object). Write the size of the object in the first sizeof(int)
bytes, invoke the constructor on the sizeof(object) bytes, return a
pointer to the object. (Perhaps there's customized allocators for
different-sized objects)

- When allocating memory for an array of objects, allocate sizeof(int) +
sizeof(int) + arraysize * sizeof(object). Write the arraysize in the
first sizeof(int) bytes, write sizeof(object) in the second sizeof(int)
bytes, invoke the constructor on each of the sizeof(object) bytes.
Return a pointer to the first object.

- When using delete, invoke the destructor on the sizeof(object) bytes
starting at the pointer, back up sizeof(int) bytes, hand this pointer
back to wherever the memory came from (perhaps some global
allocator/deallocator)

- When using delete[], back up sizeof(int) + sizeof(int). Copy out the
first sizeof(int) as the number of objects, copy the 2nd sizeof(int) for
the object size. Loop over each of the sizeof(object) bytes (starting
from the _end_ of the array) and invoke the destructor on each object in
turn. Finally hand the pointer - sizeof(int) - sizeof(int) back to
wherever the memory came from.
As a result, if you allocate with:

int * p = new int[1];

You get 12 bytes allocated, starting at p - 8. (Let's assume no padding
and sizeof(int) == 4)

When you call:

delete p;

You end up attempting to hand p - 4 back to the OS. Since it didn't
allocate that pointer, who knows what it's going to do. And in the
theoretical case where different-sized allocations come from different
pools, this memory block would be handed back to the wrong pool too (say,
the 8-byte allocator instead of the 12-byte allocator).

Dec 24 '06 #10

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

Similar topics

9
5715
by: Melissa | last post by:
What is the code to delete a command button from a form? Can the code be run from the click event of the button to be deleted? Thanks! Melissa
8
3983
by: doomx | last post by:
I'm using SQL scripts to create and alter tables in my DB I want to know if it's possible to fill the description(like in the Create table UI) using these scripts. EX: CREATE TABLE( Pk_myPrimaryKey INTEGER CONSTRAINT pk PRIMARY KEY DESCRIPTION 'This is the primary key of the table',
1
4007
by: Daveyk0 | last post by:
Hello there, I have a front end database that I have recently made very many changes to to allow off-line use. I keep copies of the databases on my hard drive and link to them rather than the live databases on the network. Is there a way, via code, when I get back in-house from being on the road to click a button, and select the backends I want to link to? I would want to delete all the current links and link to the "live"
14
4131
by: Just Me | last post by:
Can anyone fix the code below? I need to set pTo to NULL and pFrom to a fullfilepath followed by two NULLs Below Filename is a string With FileOperation ..wFunc = FO_DELETE ..pFrom = FileName??
14
1889
by: Jonas | last post by:
Hi! I'm developing the middletiers of an ASP.NET application in VB.NET. I've got a business logic layer in which I would like to perform auditing to a database. Instead of making an auditing call in every method of my classes, would it be a workable way to implement IDisposable in the base class to all the BLL-classes and then in the Dispose method to do the audit call? Do I then have to make sure that all uses of the BLL-classes end...
1
4573
by: Robert Fitzpatrick | last post by:
I am running PostgreSQL 7.4.5 and have a trigger on a table called tblriskassessors which inserts, updates or delete a corresponding record in tblinspectors by lookup of a contact id and license number match. The INSERT and DELETE work fine. The UPDATE works good unless I update the license number. The error, at the bottom of this message, suggests the primary key violation. But my UPDATE in no way alters the primary key, which is...
6
17180
by: ransoma22 | last post by:
I developing an application that receive SMS from a connected GSM handphone, e.g Siemens M55, Nokia 6230,etc through the data cable. The application(VB.NET) will receive the SMS automatically, process and output to the screen in my application when a message arrived. But the problem is how do I read the SMS message immediately when it arrived without my handphone BeEPINg for new message ? I read up the AT commands, but when getting down...
1
2378
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I look for when evaluating someone's code is a try/catch block. While it isn't a perfect indicator, exception handling is one of the few things that quickly speak about the quality of code. Within seconds you might discover that the code author...
13
5027
by: Tristan Wibberley | last post by:
Hi I've got implementing overloaded operator new and delete pretty much down. Just got to meet the alignment requirements of the class on which the operator is overloaded. But how does one implement operator new/delete I can't see a way to indicate, on delete, how many objects must be destroyed (or how big the space is) - alternatively I can't figure out what are the alignment requirements so that the implementation, after calling my...
0
8352
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
8863
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
8780
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...
0
7378
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
5661
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
4192
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...
0
4358
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2765
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
2
2005
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.