问题描述
我正在编写一个c ++程序,该程序以迭代方式实现合并排序".主要代码如下所示,即使我在另一个程序中以相同的方式分配了更多的内存(1 gb),我也无法理解为什么出现访问冲突写入位置0xXXXXXXXX"错误.
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");
}
推荐答案
您只能分配足够的内存来容纳1个整数:new int(size)
并将其分配为size
.因此,您没有a指向的1GB内存.超过1个整数访问它是未定义的行为,可能会导致访问冲突.
You allocate only memory enough for 1 integer: new int(size)
and assign it as size
. 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.
将new int(size)
更改为方括号:new int[size]
.
更好的是,使用std::vector<int>
.
这篇关于访问冲突写入位置0xXXXXXXXX的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!