Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

basic question about pointer in c++

Status
Not open for further replies.

Alexander Yin

Junior Member level 2
Joined
May 29, 2007
Messages
21
Helped
1
Reputation
2
Reaction score
0
Trophy points
1,281
Location
Finland
Activity points
1,450
I have test the following code
#include <iostream>
using namespace std;

class A
{
public:
int aa;
};


int main()
{
A *a = new A;
a->aa = 55;
A *b = new A;
b = a;
b->aa = 555;
delete b;
b= NULL;
cout<<a->aa<<endl;
delete a;
a=NULL;
return 0;
}

it has neither error nor warning when compiling but has error when executing.

after changing the main function to:
A *a = new A;
a->aa = 55;
cout<<a->aa<<endl;
A *b = new A;
b = a;
b->aa = 555;
cout<<a->aa<<endl;
delete b;
it worked as i expected.

my questions are:
1, why a cannot be deleted in the later code since once delete a, there is some error when executing although the right result can be printed.
2, why the first code is totally wrong.

thank you.
 

may be Because You assign a to b so if b delete a automatically deleted. Pl. correct me if i am wronge
 

absolutely. i just found the reason is a and b are both pointing to the same address where an object of A is stored. delete method in c++ deletes the content pointed by the pointer. after deleting b, the content at the address is removed. therefore, when the compiler tries to delete a, it will notice that the content is not valid anymore, thus reports an error.
 

Alexander Yin said:
absolutely. i just found the reason is a and b are both pointing to the same address where an object of A is stored. delete method in c++ deletes the content pointed by the pointer. after deleting b, the content at the address is removed. therefore, when the compiler tries to delete a, it will notice that the content is not valid anymore, thus reports an error.

Your programme try tries to delete a not compiler so you get run time error not compile time error
 

there is a memory leak in your first program; when you assign b=a when is separately allocated....

A *b = new A;
b = a;

this is not related to the topic but i think it would be beneficial...
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top