problems returning a dynamically allocated array from a fcn

Joined
Jan 7, 2008
Messages
3
Reaction score
0
Hi I have been getting a runtime "debug error" when I run the code below. The error occurs at the delete [] div. I have been trying multiple ways to get this to work in C++ without using vectors or anything of that sort. Any help with figuring out why this is happening, and a possible solution would really be great! Thanks

Code:
int addDivisors(int* arr)
{
	int index = 0;
	int sum = 0;
	while(arr[index] != -1)
	{
		sum += arr[index];
		index++;
	}
	return sum;
}
int* getDivisors(_int64 num)
{
	int x = divisors(num);
	int* divisors = new int[x];
	int count = 0;
	for(int i=1; i<=num; i++)
	{
		if(num % i == 0)
		{
			divisors[count]=i;
			count++;
		}
	}
	divisors[count] = -1;

	return divisors;	
}
int euler21()
{
	int MAX = 10000;
	int a[10000];
	int b[10000];
	for(_int64 i=1;i<MAX;i++)
	{
		int* div = 0;
		div = getDivisors(i);
		int sum = addDivisors(div);
		a[i-1] = b[i-1] = sum;
		delete [] div;
		div = NULL;
	}

	return 0;

}
 
Joined
Jan 7, 2008
Messages
3
Reaction score
0
If anyone is interested the cause of this error was that the dynamically allocated array was getting more elements placed inside of it then it was initialized for. For example:

int* divisors = new int[x]; // here x is 3

//later in the code
divisors[count] = -1 // here count is 3

then when the array is deleted the error occurs because I was overwriting the bounds of the array.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,079
Latest member
ElidaWarin

Latest Threads

Top