当函数loadRow(tmpPop,bestOf4Route,k,n);时,我有这段代码给我 SEGMENTATION FAULT ;称为第五次。特别是,该函数在 fro 的第一个循环中被正确调用(当 p=3 时)。对于每个 k 值,一切正常。我不明白为什么,我第二次执行循环(p = 7),第一次被调用(k = 0),当尝试访问矩阵tmpPop时它返回SEGMENTATION F。
randperm(popSize,randomOrder);
for(p = 3;p<popSize;p+=4)
{
load_rtes(rtes,pop,randomOrder,n,p);
load_dists(dists,totalDist,randomOrder,p);
find_min(dists, 4,&m,&idx);
for(j=0;j<n;j++) bestOf4Route[j]=rtes[j][idx];
X = rand_range(1,5);
Y = rand_range(1,5);
for(k =0;k<4;k++) //Mutate the Best to get Three New Routes
{
loadRow(tmpPop,bestOf4Route,k,n);
switch(k)
{
case 1: //Flip
flipMutation(tmpPop,k,X,Y);
break;
case 2: //Swap
swapMutation(tmpPop,k,X,Y);
break;
case 3: //Slide
slideMutation(tmpPop,k,X,Y);
break;
}
}
loadnewPop(newPop,tmpPop,p,n);
}
功能是:
void loadRow(int **mat,int *array,int k,int size)
{
int j;
for(j=0;j<size;j++)
{
mat[j][k] = array[j];
}
}
参数是:
弹出大小 = 16
n= 8
// create 4 x N matrix
tmpPop = (int**)malloc(n * sizeof(int*));
if(tmpPop==NULL) return 1;
for (i = 0; i < n; i++) {
tmpPop[i] = (int*)malloc(4 * sizeof(int));
if(tmpPop[i]==NULL) return 1;
}
// Creates an array of n
bestOf4Route = (int*)malloc(n * sizeof(int));
if(bestOf4Route==NULL) return 1;
clear_array(bestOf4Route,n);
而她是调试结果:
00401865 loadRow(mat=0x3e1438, array=0x3e1698, k=0, size=8)
void load_rtes(int **rtes,int **pop,int *randomOrder, int n,int p)
{
int i,j,r;
for(i=p-3;i<=p;i++)
{
//thakes the i element of randomOrder and use it as index for the pop row
r=randomOrder[i];
// copy the pop row in rtes
for(j=0;j<n;j++)
{
rtes[j][i]=pop[j][r];
}
}
}
void randperm(int n,int *perm)
{
int i, j, t;
for(i=0; i<n; i++)
perm[i] = i;
for(i=0; i<n; i++) {
j = rand()%(n-i)+i;
t = perm[j];
perm[j] = perm[i];
perm[i] = t;
}
}