在数组中检查索引后程序崩溃



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

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

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

我正在尝试以下代码:

#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。然后在尝试读取成本[693778120]后,它关闭。目前,我不担心效率,也不担心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;
}

问题仍然存在

如果以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;

我得到了一个坏地址,因为我的交换磁盘不够大。