Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamically Allocated Arrays of Objects

Status
Not open for further replies.

bsuribabu

Programmer
Apr 4, 2002
25
IN
Hi,

Please pls look at this code.

#include <iostream>
using namespace std;

int main()
{
int *pi;
pi = new int[5];
pi++;
delete[] pi;
}

can i do like this ?
What are the consequences for this stub.

Suri
 
NO... this will cause problems, here is why

int* pi; // declare a pointer to an int
pi = new int[5]; // pi points to an array of 5 ints

// ok here lets say that pi's memory address is 123

pi++; // pointer arithmetic, pi now points to 124

delete[] pi;

// this call to delete will delete starting at 124 and NOT 123

Matt
 
Well, the consequence for this &quot;stub&quot; is that your programm will crash. Simply said. :)

As Matt already said, delete will begin deleting at (pseudo) address 124 and it tries to delete 5 &quot;ints&quot;.
This causes a memory error, which leads to the crash.

Greetings,
Flo
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top