[cs13001] FW: Deallocating Part of an Array
Mikhail Nesterenko
mikhail at cs.kent.edu
Thu Mar 21 16:16:45 EDT 2013
There was a discussion in class whether it is possible to deallocate
part of the array. For example:
int *p=new[20]; // allocate an array of 20 elements
int *p2 = p+10; // point a second pointer to mid-array
delete [] p2; // try to deallocate the "tail" of the array
Below is an answer from stackoverlfow. The answer is no, it is not correct.
> Sent: Wednesday, March 20, 2013 7:24 PM
> To: NESTERENKO, MIKHAIL
> Subject: Deallocating Part of an Array
>
> These guys say it?s a bad idea.
>
> http://stackoverflow.com/questions/7747843/c-deleting-part-of-dynamic-array
>
> It has something to do with this being an undefined behavior. The work-abounds all involve deallocating the entire array and reallocating a new one.
I consulted Bjarne Stroustrup's book. In general, C++ does not
distinguish between a pointer to an individual element and an
array. However, for heap implantation purposes, it is
significant. Hence, the only correct deallocation operation on
dynamically allocation array is "delete [] addressOfTheFirstElement;"
Everything else leads to unpredictable behavior. For example
// allocation
int *t1 = new int; // individual element
int *t2 = new int[size]; // array of size "size"
int *t3 = new int;
int *t4 = new int[size];
// deallocation
delete t1; // correct
delete [] t2; // correct
delete [] t3; // incorrect, unspecified behavior
delete t4; // incorrect, unspecified behavior
On a related subject. Note, that for lab 10 (and 11), in your
addNumber() and removeNumber() functions you will have to consider a
special case where the array is empty (hence, the array pointer
arrayPtr is uninitialized). One way to handle it is to write code that
checks and handles this case explicitly.
Alternatively, it is possible to allocate zero-length array. That is,
the below operation is correct:
int *arrayPtr = new[0];
This way, the case of empty(zero-element) array can be handled the
same way as non-empty array which should simplify the code for your
addNumber() and removeNumber() functions.
Thanks,
--
Mikhail
More information about the cs13001
mailing list