473,698 Members | 2,086 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on delete [] vs just plain delete

Hi,

I am new to c++. I recently spend an enormous among of time
troubleshooting a seeminly innocuous piece of code. Although I narrow
down this piece of code as the culprit but I don't understand why. Can
some guru help to enlighten me? Thank you.

// I created an array of pointers to object pointers:

Object ** obs = new Object * [9];

// After that I populate this array:

for(int i=0; i<9; i++){
obs[i] = new Object(i);
}

// After using them i deleted the array:

for(int i=0; i<9; i++){
delete obs[i];
}

delete [] obs;

delete obs; // this is the problem, during execution the program
hanged.

Apparently, the above caused undefined behaviour. But I don't know why
i shouldn't do that. Thanks again for any sharing!

Cheers,
Damon

Jul 23 '05 #1
11 1782
"DamonChong " <so********@exc ite.com> wrote in message
news:11******** *************@c 13g2000cwb.goog legroups.com...
Hi,

I am new to c++. I recently spend an enormous among of time
troubleshooting a seeminly innocuous piece of code. Although I narrow
down this piece of code as the culprit but I don't understand why. Can
some guru help to enlighten me? Thank you.
While the gurus answer more difficult questions, I'll field this one.

// I created an array of pointers to object pointers:

Object ** obs = new Object * [9];
/////////// Great, you've allocated an array of pointers to Object

// After that I populate this array:

for(int i=0; i<9; i++){
obs[i] = new Object(i);
/////////// And now you've allocated the objects. }

// After using them i deleted the array:

for(int i=0; i<9; i++){
delete obs[i];
/////////// Now you've deallocated the objects.
}

delete [] obs;
/////////// And now you've deallocated the array.
/////////// Good. So you've deallocated everything you've allocated. Nothing
left to deallocate.

/////////// and yet....
delete obs; // this is the problem, during execution the program
hanged.


/////////// So the previous line hangs since you're deallocating something
which you shouldn't

Jul 23 '05 #2
Hi Damon

Efrat already answered your post, but I will recommend you do not use
new/delete as a newbie C++ programmer. Instead focus on the standard library
and just don't use pointers.
Pointers are difficult and better not used until you understand the basics
of C++ - including the standard library. By going this route, you will also
learn how little use there actually is of pointers in modern C++.

/Peter
"DamonChong " <so********@exc ite.com> skrev i en meddelelse
news:11******** *************@c 13g2000cwb.goog legroups.com...
Hi,

I am new to c++. I recently spend an enormous among of time
troubleshooting a seeminly innocuous piece of code. Although I narrow
down this piece of code as the culprit but I don't understand why. Can
some guru help to enlighten me? Thank you.

// I created an array of pointers to object pointers:

Object ** obs = new Object * [9];

// After that I populate this array:

for(int i=0; i<9; i++){
obs[i] = new Object(i);
}

// After using them i deleted the array:

for(int i=0; i<9; i++){
delete obs[i];
}

delete [] obs;

delete obs; // this is the problem, during execution the program
hanged.

Apparently, the above caused undefined behaviour. But I don't know why
i shouldn't do that. Thanks again for any sharing!

Cheers,
Damon

Jul 23 '05 #3
ajk
On 29 Jan 2005 01:39:32 -0800, "DamonChong " <so********@exc ite.com>
wrote:
delete [] obs;

delete obs; // this is the problem, during execution the program

normally you use delete [] on any array you allocate to tell the
compiler that the ptr you are deleting is an array.

it is just one of those not obvious c++ rules you need to learn :)

in any case I would suggest you use vector<> instead of array since it
is safer and more convenient. check up the online help/book for info.
STL in general can help you a lot.

/ajk
--
"Those are my principles. If you don't like them I have others."
Groucho Marx.
Jul 23 '05 #4
Thanks alot. Kind of silly I suppose to make such mistake. ;P

Jul 23 '05 #5
"DamonChong " <so********@exc ite.com> wrote in message
news:11******** **************@ c13g2000cwb.goo glegroups.com.. .
Thanks alot. Kind of silly I suppose to make such mistake. ;P


No problem. BTW, explicit memory management is both very powerful, and
very prone to making "silly" mistakes (which I don't think are silly at
all). Consequently, perhaps you might want to read Peter Koch Larsen's
response (with which I completely agree).

Specifically, you could write your code this way:

#include <vector>

std::vector<Obj ect> obs[9];

for(int i = 0; i < 9; ++i)
obs[i] = Object(i);

Or if Object doesn't have a default constructor,

#include <vector>
#include <boost/shared_ptr.hpp>

std::vector<boo st::shared_ptr< Object> > obs(9);

for(int i = 0; i < 9; ++i)
obs[i].reset(new Object(i));

(You could google for boost smart_ptr for the above).
Jul 23 '05 #6
Jon
While I would agree that pointers are maybe not obvious for a beginner to
say that there is "little use" of pointers in modern c++ is just plain wrong
in my opinion. Of course it maybe depends on what you define as "modern c++"
but that is another question...

"Peter Koch Larsen" <pk*****@mailme .dk> wrote in message
news:%j******** ************@ne ws000.worldonli ne.dk...
Hi Damon

Efrat already answered your post, but I will recommend you do not use
new/delete as a newbie C++ programmer. Instead focus on the standard
library and just don't use pointers.
Pointers are difficult and better not used until you understand the basics
of C++ - including the standard library. By going this route, you will
also learn how little use there actually is of pointers in modern C++.

/Peter
"DamonChong " <so********@exc ite.com> skrev i en meddelelse
news:11******** *************@c 13g2000cwb.goog legroups.com...
Hi,

I am new to c++. I recently spend an enormous among of time
troubleshooting a seeminly innocuous piece of code. Although I narrow
down this piece of code as the culprit but I don't understand why. Can
some guru help to enlighten me? Thank you.

// I created an array of pointers to object pointers:

Object ** obs = new Object * [9];

// After that I populate this array:

for(int i=0; i<9; i++){
obs[i] = new Object(i);
}

// After using them i deleted the array:

for(int i=0; i<9; i++){
delete obs[i];
}

delete [] obs;

delete obs; // this is the problem, during execution the program
hanged.

Apparently, the above caused undefined behaviour. But I don't know why
i shouldn't do that. Thanks again for any sharing!

Cheers,
Damon


Jul 23 '05 #7

My question is why dynamically allocate an array of Object pointers. Why not
just just

Object *obparray[9];

??

Is memory that sparse now days?

"DamonChong " <so********@exc ite.com> wrote in message
news:11******** *************@c 13g2000cwb.goog legroups.com...
Hi,

I am new to c++. I recently spend an enormous among of time
troubleshooting a seeminly innocuous piece of code. Although I narrow
down this piece of code as the culprit but I don't understand why. Can
some guru help to enlighten me? Thank you.

// I created an array of pointers to object pointers:

Object ** obs = new Object * [9];

// After that I populate this array:

for(int i=0; i<9; i++){
obs[i] = new Object(i);
}

// After using them i deleted the array:

for(int i=0; i<9; i++){
delete obs[i];
}

delete [] obs;

delete obs; // this is the problem, during execution the program
hanged.

Apparently, the above caused undefined behaviour. But I don't know why
i shouldn't do that. Thanks again for any sharing!

Cheers,
Damon

Jul 23 '05 #8
"Bradley" <bn*****@kc.rr. com> wrote in message
news:fl******** *************@t wister.rdc-kc.rr.com...

My question is why dynamically allocate an array of Object pointers. Why not just just

Object *obparray[9];

??

Is memory that sparse now days?


It's possible that Object doesn't have a default constructor.
Jul 23 '05 #9

"Efrat Regev" <ef*********@ya hoo.com> wrote in message
news:xO******** ************@ad elphia.com...
"Bradley" <bn*****@kc.rr. com> wrote in message
news:fl******** *************@t wister.rdc-kc.rr.com...

My question is why dynamically allocate an array of Object pointers. Why

not
just just

Object *obparray[9];

??

Is memory that sparse now days?


It's possible that Object doesn't have a default constructor.


Oops! my bad - I misunderstood your post.
Jul 23 '05 #10

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

Similar topics

4
2890
by: Shea Martin | last post by:
Which of the following do I use delete instead of just delete. //1.) // not sure about this one, as char is of size 1 char *str = new char; //2.) //not sure about this one, as it is a primitive int *array = new int;
3
1402
by: lallous | last post by:
Hello Consider this: // allocate a buffer, and cast to MYSTRUCT MYSTRUCT *p = (MYSTRUCT *) new char; // free the buffer // 1. can I free directly as:
7
1562
by: MSG Servicos de Informatica | last post by:
Hi MSDN Team! I have a doubt about the "MailMessage" class in Framework .NET 1.1. My SMTP server works in a local network that no have access to the internet for security reasons. And in my network we have an application that send emails to other department inside the company using us SMTP server that requires authentication... I'd like to know why when I use the "MailMessage" Class with "SMTPServer" class to authenticate in my SMTP...
12
2036
by: dennist685 | last post by:
Can't edit, delete or add row in an Access database in a website 2003 When I implement a walkthrough using Northwind I have no trouble doing this. Also, in a windowsforms project I have no problem editing, adding or deleting rows. But in webforms the smarttags don't offer the options. Can anybody help?
10
3719
by: Rider | last post by:
Hi, simple(?) question about asp.net configuration.. I've installed ASP.NET 2.0 QuickStart Sample successfully. But, When I'm first start application the follow message shown. ========= Server Error in '/QuickStartv20' Application. -------------------------------------------------------------------------------- Configuration Error Description: An error occurred during the processing of a configuration file
3
13744
by: NateDawg | last post by:
I'm reposting this. I'm kinda in a bind untill i get this figured out, so if anyone has some input it would sure help me out. Ok, I’ve noticed a few gridview problems floating around the forum. Everyone wants to do a java confirmation box when a user clicks the delete button. Fair enough, basic user design rules state that you should always confirm a delete action. There is also a consensus that the best way to do this is a template...
9
2413
by: CGW | last post by:
I asked the question yesterday, but know better how to ask it, today: I'm trying to use the File.Copy method to copy a file from a client to server (.Net web app under IIS ). It looks to me that when I give a path like @"C:\holdfiles\myfile.txt" it looks on the server C drive. How do I pull from the client? Do I need a different class and/or method? Filestream? -- Thanks,
7
7020
by: AB | last post by:
Hi all, A thought crossed my mind.... if I allocate memory for an array at runtime using.... int* arr = new int ; what happens when I then de-allocate memory using
25
2395
by: eggie5 | last post by:
I have a form where a user can change his password, but I'm confused on how to prevent this from being transmitted in plain text. Well, I know how not to transmit it in plain text - use any type of encryption, but then the problem is, how do I decrypt it on the server to store it? If I use some type of key based encryption, the how do I get the key to the client without it being intercepted, rendering the whole process useless.
0
8604
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
9157
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
8895
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
8861
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
5860
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
4369
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
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3046
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
2001
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.