I am writing a c++ program implementing the Merge Sort iteratively. The main code is shown below and I cannot understand why I am having the “Access violation writing location 0xXXXXXXXX” error, even though I allocated much more memory (1 gb) in the same way in another program.
void main()
{
//int a[size];
int* a = new int(size); //initialising an int array dynamically contains 16777216 el
srand(time(NULL));
for(int i = 0 ; i < size; i++)
{
a[i]= 1 + rand() % 10;
}
for(int i = 0; (size / 2) / pow((double)2, i)>= 1; i++)
{
int n = pow((double)2, i);
int offset = 0;
for(int j = 0; j < (size / 2) / pow((double)2, i); j++)
{
int* tmp = new int(n);
merge(a + offset, n, a + offset + n, n, tmp);
memcpy(a + offset, tmp, n*2 * sizeof(int));
offset += pow((double)2, i+1);
}
}
for(int i = 0; i < size; i++)
{
cout<<a[i]<<" ";
//printf("%d ", a[i]);
}
cout<<endl;
system("PAUSE");
}
You allocate only memory enough for 1 integer:
new int(size)and assign it assize. So you don’t have 1GB of memory pointed by a. Accessing it beyond 1 integer is undefined behavior, which can give you an access violation.Change
new int(size)to square brackets:new int[size].And better still, use a
std::vector<int>.