【问题标题】:Program crashes after checking index at array检查数组索引后程序崩溃
【发布时间】:2021-01-19 19:25:01
【问题描述】:

请注意:我不确定这是否适合这里,如果不适合,请转到正确的论坛。

所以我有一个程序试图解决旅行商问题,简称 TSP。

我的代码似乎运行良好,直到我尝试使用 33810 个城市,其中程序在尝试访问位置成本 [69378120] 后崩溃,它只是停止响应并很快结束。

我正在尝试以下代码:

  #include <iostream>
  #include <stdlib.h>
  #include <malloc.h>
  #include <fstream>
  #include <math.h>
  #include <vector>
  #include <limits>

  using namespace std;

  typedef long long int itype;


  int main(int argc, char *argv[]) {

    itype n;
    ifstream fenter;
  fenter.open(argv[1]);
  ofstream fexit;
  fexit.open(argv[2]);
  fenter>> n;
  double *x;
  double *y;
  x = (double*) malloc(sizeof(double)*n);
  y = (double*) malloc(sizeof(double)*n);
    cout<<"N : "<<n<<endl;
  for (int p = 0; p < n; p++) {
    fenter>> x[p] >> y[p];
  }
  fenter.close();

  int *costs;
  costs = (int*) malloc(sizeof(int)*(n*n));
  for (int u = 0; u < n; u++) {
    for (int v = u+1; v < n; v++) {
      itype cost = floor(sqrt(pow(x[u] - x[v], 2) + pow(y[u] - y[v], 2)));
      cout<<"U: "<<u<<"   V: "<<v<<"    COST: "<<cost<<endl;
      costs[u*n + v] = cost;
      cout<<"POS (u*n + v): "<<(u*n + v)<<endl;
      cout<<"POS (v*n + u): "<<(v*n + u)<<endl;
      costs[v*n + u] = cost;
    }
  }
  return 0;
}

根据一些验证,成本数组应该使用 9.14493GB,但 Windows 仅给出 0.277497GB。然后在尝试读取成本 [69378120] 后,它会关闭。 目前,我不担心效率,也不担心 TSP 的解决方案,只需要解决这个问题。有什么线索吗?

---更新--- 根据建议,我尝试更改一些内容。结果是下面的代码

int main(int argc, char *argv[]) {

int n;
ifstream entrada;
entrada.open(argv[1]);
ofstream saida;
saida.open(argv[2]);
entrada >> n;
vector<double> x(n);
vector<double> y(n);

for (int p = 0; p < n; p++) {
    entrada >> x[p] >> y[p];
}
entrada.close();

vector<itype> costs(n*n);
if(costs == NULL){ cout << "Sem memória!" << endl; return -1;}


for (int u = 0; u < n; u++) {
for (int v = u+1; v < n; v++) {
    itype cost = floor(sqrt(pow(x[u] - x[v], 2) + pow(y[u] - y[v], 2)));
  costs[u*n + v] = cost;
  costs[v*n + u] = cost;
}
}
return 0;
}

问题依旧

【问题讨论】:

标签: c++ windows memory


【解决方案1】:

如果编译成 32 位 size_t 是 32 位然后

1143116100*4

大于最大的 32 位数字,因此 int 溢出。

64 位编译

size_t siz = 1143116100;
std::vector<long long> big(siz);
std::cout << big.size() << ", " << big.max_size() << std::endl;

打印出来的

1143116100, 2305843009213693951

如果我把它改成

size_t siz = 1024*1143116100;

我得到一个 bad_alloc,因为我的交换磁盘不够大。

【讨论】:

  • 确实是 x32 和 x64 的问题,我改成 Visual Studio 兼容 x64 似乎解决了问题,感谢所有指出的。
猜你喜欢
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 2013-05-30
  • 1970-01-01
  • 2016-02-11
相关资源
最近更新 更多