Original Post
🔒 Locked
Pointer Array Problem
Advertisement
You initialise the pointer to point to four newly allocated integers on the heap. These, however, you throw away by making the pointer point to the first element of the statically allocated array (leaking the memory for the first four integers). When you then attempt to delete the data at the pointer, you are trying to deallocate memory on the stack!
There is no need to initialise the pointer to memory created with new if you intend to make it point to something statically allocated, as here. (It may be a good idea to initialise each pointer to 0 if you cannot immediately assign something meaningful to it.)
There is no need to initialise the pointer to memory created with new if you intend to make it point to something statically allocated, as here. (It may be a good idea to initialise each pointer to 0 if you cannot immediately assign something meaningful to it.)
Ok, you've got two arrays.
array1, and a unnamed array you allocate with new int [4];
Lets call the memory for array1 [int4_A] and the currArray new'd memory [int4_B]
So:
then you fill [int4_A] with numbers
then this line:
now it looks like this:
So now array1 and currArray both mean the first array.
Nothing points to the second, so you've just leaked that memory.
Then when you call this:
delete [] currArray;
You're trying to delete array1, not the [int4_B]!
Which you can't , since you didn't create that memory with new,
it was created by entering the function (and it will be deleted
when you exit the function).
So just change this:
to:
Since you're trying to manipulate a static array, there's no reason to allocate more memory.
Then just leave out the
line.
It should work fine then.
[edited by - TravisWells on February 16, 2003 7:07:30 PM]
array1, and a unnamed array you allocate with new int [4];
Lets call the memory for array1 [int4_A] and the currArray new'd memory [int4_B]
So:
array1->[int4_A]
currArray->[int4_B]
then you fill [int4_A] with numbers
then this line:
currArray = array1;
now it looks like this:
array1->[int4_A]
currArray ->[int4_A]
[int4_B]
So now array1 and currArray both mean the first array.
Nothing points to the second, so you've just leaked that memory.
Then when you call this:
delete [] currArray;
You're trying to delete array1, not the [int4_B]!
Which you can't , since you didn't create that memory with new,
it was created by entering the function (and it will be deleted
when you exit the function).
So just change this:
int *currArray = new int[4];
to:
int *currArray=array1;
Since you're trying to manipulate a static array, there's no reason to allocate more memory.
Then just leave out the
currArray = array1;
line.
It should work fine then.
[edited by - TravisWells on February 16, 2003 7:07:30 PM]
just do:
currArray = array2;
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement