I was trying to see if my code for copying an array worked when I got this scary looking error message:

Debug Assertion failed!

Program: ...dio 2008\Projects\Test_Prep\Test_prep.exe
File: f:\dd\vctools\crt_bld\self_x86\srt\dbgdel.cpp
Line: 52

Expression _BLOCK_TYPE_IS_VALID(pHead->nBlockUse)


Here's my testing code and the function I wrote:

int main()
{	
	const int MAX_SIZE = 5;
	int List[ MAX_SIZE ] = { 1, 2, 3 };
	cout << List[ 2 ];
	cout << endl << endl;
	cout << *CopyArray( List , 5 );
	HoldScreen();

	
}

int *CopyArray( int List[ ], int Size )
{
	
	int NewSize = Size;
	int *NewList = new int [Size];
	for ( int Index = 0 ; Index < Size ; ++Index )
		NewList[ Index ] = List[ Index ];
		delete [] List;
		List = NewList;
		return NewList;
}

I think I'm messing up on the parameters in main?

Whenever you 'delete' something, that something must have been allocated using the 'operator new', without exceptions. The delete [] List; does the damage which is reported.

Looking at your code, it looks like your intention is to simultaneously return a pointer to the
"copied" array and clean up the memory allocated by the old array. Having a function perform that task for you can be troublesome because your code doesn't know whether the old array is allocated dynamically (on the heap) or not. As your code is, the old list is allocated on the stack -- it is deleted automatically.

If your old list were to be allocated dynamically, like:

int *List = new int[MAX_SIZE]();
List[0] = 1;
List[1] = 2;
List[2] = 3;

Then your function, as is, would work fine. Or, as was mentioned, you could change your function to simply not delete the old array. I think that's a pretty good idea, because it's usually the programmer's responsibility to delete anything they allocate onto the heap. If you imagine someone else using your function, they would probably know best if they needed to delete the old list manually or not.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.