如何解决“无法访问地址c ++的内存”问题

时间:2019-07-06 09:40:16

标签: c++ memory-leaks stack-overflow

我从Eclipse IDE中收到以下错误,但是我不确定如何解决该问题。有人可以给我任何建议吗?我是编码新手。

尝试了不同的IDE。我的代码在在线IDE上有效,但在其他IDE上无效。

using namespace std;
using namespace std::chrono;

void Swap(int *x,int *y) {
int temp=*x;
*x=*y;
*y=temp;
}

void Insertion(int A[],int n) {
    int i,j,x;
    for(i=1;i<n;i++) {
        j=i-1;
        x=A[i];
        while(j>-1 && A[j]>x){
            A[j+1]=A[j];
            j--;
        }
        A[j+1]=x;
    }
}

void Merge(int A[],int l,int mid,int h) {
    int i=l,j=mid+1,k=l;
    int B [500000];
    while(i<=mid && j<=h) {
        if(A[i]<A[j])
            B[k++]=A[i++];
        else
            B[k++]=A[j++];
    }
    for(;i<=mid;i++) {
        B[k++]=A[i];
    }
    for(;j<=h;j++) {
        B[k++]=A[j];
    }
    for(i=l;i<=h;i++) {
        A[i]=B[i];
    }
}

void MergeSort(int A[],int l,int h) {
    if(l<h) {
        int mid=(l+h)/2;
        MergeSort(A,l,mid);
        MergeSort(A,mid+1,h);
        Merge(A,l,mid,h);
    }
}

void ArrayAscend (int A[], int n) {
    for (int a = 0; a < n ; a++) {
        A [a] = a + 1;
    }
}

void ArrayRandom (int A[], int n) {
       ArrayAscend (A,n);
       srand (time(NULL));
       for (int  i= n-1 ; i > 0; i--) {
              int j = rand () % (i+1);
              Swap (&A[i], &A[j]);
       }
}

void ArrayDescend (int A[], int n) {
       for (int a = 0; a < n ; a++) {
        A [a] = n - a;
    }
} 

int main() {


   int arraySize500000 = 500000;
   int array500000[arraySize500000] = {};


  cout << "*********************Insertion Sort*********************" <<endl;

  cout << "---------- Arrays with 500000 Integers ----------" <<endl;

  ArrayAscend (array500000,arraySize500000);
  auto t1 = system_clock::now();
  Insertion(array500000,arraySize500000);
  auto t2 = system_clock::now();
  auto duration1 = duration_cast<microseconds>(t2-t1);
  cout << "Array in ascending order took " << duration1.count()<<" microseconds"<<endl;

  ArrayDescend (array500000,arraySize500000);
  auto t3 = system_clock::now();
  Insertion(array500000,arraySize500000);
  auto t4 = system_clock::now();
  auto duration2 = duration_cast<microseconds>(t4-t3);
  cout << "Array in descending order took " << duration2.count()<<" microseconds"<<endl;

  ArrayRandom (array500000,arraySize500000);
  auto t5 = system_clock::now();
  Insertion(array500000,arraySize500000);
  auto t6 = system_clock::now();
  auto duration3 = duration_cast<microseconds>(t6-t5);
  cout << "Array in random order took " << duration3.count()<<" microseconds"<<endl;

return 0;
}

我希望每个插入类型的持续时间输出。但是,调试时出现以下错误。

无法执行MI命令: -data-evaluate-expression *((数组500000)+30000)@ 10000 来自调试器后端的错误消息: 无法访问地址0x42f250的内存

1 个答案:

答案 0 :(得分:1)

int B [500000];
int arraySize500000 = 500000;
int array500000[arraySize500000] = {};

即使将其转换为constexpr,正如John指出的那样,它们也会在堆栈上创建2MB的数组。例如,Visual Studio仅分配了1MB of stack

您应该改用std::vector<int> array500000(500000)