Reputation: 107
I'm currently learning about pointers in my C++ book (Programming: Principles and Practice using C++ by Stroustrup). The book had me do the following 'drill' to become accustom to pointers and arrays. I've commented parts of the drill that aren't relevant to my issue.
int num = 7;
int* p1 = #
// output p1 address and content...
int* p2 = new int(10);
// initialise each element, and output content...
int* p3 = p2;
p1 = p2;
// output p1 and p2 address and content...
delete[] p1;
/* As all pointers now point to the same array created in the free store,
I was under the impression that I only needed to use delete for 1 of
the pointers to deallocate memory,as above, but the program crashes
if I don't do it for all 3 and execute next section of code? */
p1 = new int(10);
p2 = new int(10);
// Initialise each array to a different range of numbers using a loop,
// output each array, change elements in p2 to be the same as p1, output...
delete[] p1;
delete[] p2;
The last part is where I am having trouble. When outputting each array, the elements values are the same. My guess is that p1 still == p2, due to the code a few lines before. I thought that when you use the 'new' keyword it returns an address, referencing a different, newly allocated block of memory and therefore p1 would no longer == p2. The only way I got it to work was to directly create 2 arrays and have p1 and p2 reference them using the & operator. Any explanation as to what I'm doing wrong is appreciated.
Upvotes: 0
Views: 100
Reputation: 2318
The problem probably stems from the fact that when you say
p = new int(10)
you are allocating just ONE integer and initializing it to 10, not an array of size 10.
Upvotes: 2
Reputation: 258558
int* p2 = new int(10);
// initialise each element, and output content...
int* p3 = p2;
p1 = p2;
// output p1 and p2 address and content...
delete[] p1;
This code leads to undefined behavior, because you allocate with new
and free the memory with delete[]
.
int* p2 = new int(10);
//allocates a single int with value 10
is different from
int* p2 = new int[10];
//allocates an uninitialized array of 10 ints
That aside (although a serious issue, as all undefined behavior), the problem was this:
int* p2 = new int(10);
int* p3 = p2;
p1 = p2;
//all pointer point to the same memory location
delete[] p1;
//delete that memory
//all three pointers are now invalid
Attempting to free the memory again via delete p2
or delete p3
will again lead to undefined behavior, and probably a crash, since you already deleted that memory. That is why allocating new memory will fix the crash.
Bottom line: don't free the same memory multiple times.
Upvotes: 2