Reputation: 21
I use gsl random generator to generate 2 big matrices, and use gsl cblas to multiply them, but I always got Segmentation fault when the cblas operation begins. When I can't solve this, I then write the code below, using the very basic idea to do matrix multiplication, and I still got Segmentation Fault, but all the two can work all right when matrix is really a small one, I'm really puzzled about this.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
#define PI 3.1415926
void GenerateKey(int m, int n, int l, int q, float alpha)
{
// initialization
int i;
int j;
int k;
float *A;
float *S;
float *E;
float *B;
float sigma = (alpha * q ) / sqrt(2 * PI);
A=(float*)malloc(sizeof(float)*(m*n));
S=(float*)malloc(sizeof(float)*(n*l));
B=(float*)malloc(sizeof(float)*(m*l));
E=(float*)malloc(sizeof(float)*(m*l));
// init A
for(i = 0; i < m*n; i++)
{
A[i]=0;
}
printf("\n");
// init S
for(i = 0; i < n*l; i++)
{
S[i]=0;
}
printf("\n");
// init E
for(i = 0; i < m*l; i++)
{
E[i]=0;
}
printf("\n");
float po;
for(i = 0; i < m; i++)
{
for(j=0; j<l; j++)
{
po=0;
for(k=0; k<n; k++)
{
po +=A[i*m+k]*S[k*n+j];
}
po += E[i*m +j];
B[i*m+j]=((int)po) % q;
}
}
printf("Game over");
printf("\n");
free(A);
free(B);
free(S);
free(E);
}
int main()
{
GenerateKey(2680,191,64,72973,0.000551);
return 0;
}
Upvotes: 1
Views: 405
Reputation: 8594
You incorrectly compute an element index for all the matrices.
When you have an MxN
matrix which is allocated as an 1-dimensional array, the index for an element (i,j)
is i*N+j
. Instead, you're computing it as i*M+j
.
Upvotes: 1
Reputation: 5240
When you're doing i*m+j
, shouldn't that be i*l+j
? Similarly with i*m+k
should be i*l+k
and k*n+j
should be k*l+j
The reason being, take for example E = (float*)malloc(sizeof(float)*(m*l))
, so you have m
rows and l
columns (or vise versa), so if you are iterating over the m
dimension you need to be multiplying your m
iterator (i
in this case) by the stride of your matrix in that dimension, which is l
.
Upvotes: 3
Reputation: 399753
You don't check the malloc()
return values, so my guess is that one or more allocation is failing and you're dereferencing NULL
. Another possibility is of course an indexing error, so you acccess out of bounds.
Upvotes: 1