我使用malloc时遇到问题.
我有一个叫做jacobi_gpuwich 的函数被多次调用:
int main(int argc, char* argv[]){
/* ... */
int totalrot=0;
while(nrot>0){
iter++;
nrot=jacobi_gpu(a,q, tol, dimmat);
totalrot+=nrot;
printf("iter =%3d nrot=%3d\n",iter, nrot);
}
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
参数a,q,tol和dimmat被正确初始化.A和Q是2平方矩阵,dimmat是它们的维度.
这是我的代码:
int jacobi_gpu(double A[], double Q[], double tol, long int dim){
int nrot, p, q, k, tid;
double c, s;
double *mc, *vc;
printf("jacobi begins \n");
mc = (double *)malloc(2 * dim * sizeof(double));
vc = (double *)malloc(2 * dim * sizeof(double));
if( mc == NULL || vc == NULL){
fprintf(stderr, "pb allocation matricre\n");
exit(1);
}
nrot = 0;
for(k = 0; k < dim - 1; k++){
eye(mc, dim);
eye(vc, dim);
for(tid = 0; tid < floor(dim /2); tid++){
p = (tid + k)%(dim - 1);
if(tid != 0)
q = (dim - tid + k - 1)%(dim - 1);
else
q = dim - 1;
//printf("p = %d | q = %d\n", p, q);
if(fabs(A[p + q*dim]) > tol){
nrot++;
symschur2(A, dim, p, q, &c, &s);
mc[2*tid] = p; vc[2 * tid] = c;
mc[2*tid + 1] = q; vc[2*tid + 1] = -s;
mc[2*tid + 2*(dim - 2*tid) - 2] = p;
vc[2*tid + 2*(dim - 2*tid) - 2 ] = s;
mc[2*tid + 2*(dim - 2*tid) - 1] = q;
vc[2 * tid + 2*(dim - 2*tid) - 1 ] = c;
}
}
affiche(mc,dim,2,"Matrice creuse");
affiche(vc,dim,2,"Valeur creuse");
}
printf("end\n");
free(mc);
free(vc);
return nrot;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是在moc变量上的malloc调用:
*** glibc detected *** ./jacobi_gpu: double free or corruption (!prev): 0x00000000022944a0 ***
*** glibc detected *** ./jacobi_gpu: malloc(): memory corruption: 0x0000000002294580 ***
Run Code Online (Sandbox Code Playgroud)
有什么建议?
[编辑]
矩阵mc的目的是存储变量p和q.这些变量包含列索引.矩阵vc的目的是存储这些列中包含的值.例如,如果矩阵mc的第一行是0和5(p = 0,q = 5),这意味着矩阵vc中的值将在第0列和第5列中.如果矩阵中的第五行是矩阵mc是2 3(p = 2,q = 3),这意味着vc中第五行中的值将在第2列和第3列中.
希望这一次,我更清楚.
谢谢你的帮助
身份矩阵总是正方形,但mc不是.当你打电话的时候,eye(mc, dim)我怀疑眼睛对待mc,因为当它实际上是一个2乘以昏暗的矩阵时它是昏暗的矩阵,并写入未分配的内存.