operator new[] allocates only one element regardless of how many are requested (C++) [duplicate]-Collection of common programming errors
For an introductory C++ course assignment (due tonight, of course!), I have to implement my own Vector class. Most everything seems to be working, except that I noticed in VS2012’s debugger that it appears that only one element in _arr[] actually is being allocated. Regardless of the number (n) of elements requested, it only allocates a single element in the array. I followed the debug trace, and new[] is receiving 20 for the request (the requested 5 elements * 4 bytes for an int), but when I check sizeof(_arr) later, it only shows 4 bytes. Where did the other 16 bytes end up? Why are the other 4 elements missing? No errors are indicated, and no exceptions are thrown.
template
void Vector::Add ( const T& val )
{
// Check if a new element would grow beyond the current allocation.
if ( _length + 1 > _allocSize )
{
size_t n = 5; // 0 )
for( size_t idx = 0; idx < _length; idx++ )
newArr[idx] = _arr[idx];
// Delete any dynamic memory allocated to the old array.
delete[] _arr;
// Note: _sizeof(newArr) here indicates only 4 bytes!!!
// Point _arr to the new array
_arr = newArr;
// Update the allocated size to the new array size
_allocSize = n;
}
catch ( VectorException &cException )
{
cerr