Segmantation fault when adding elements to a structure
Why do I get segmentation fault in this function:
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
vec_t mtrx_multiple (sparse_mat_t a, vec_t c) {
vec_t result;
int i;
result.n = a.n;
printf("result.n: %d\n", result.n);
result.vec = malloc(a.n * sizeof *result.vec);
for(i=0; i<a.n; i++)
result.vec[i] = c.vec[i] * a.a[a.ja[i]];
return result;
}
The structure is:
typedef struct 开发者_StackOverflow{
int n;
int *vec;
} vec_t;
typedef struct {
int *a;
int *ia;
int *ja;
int n;
} sparse_mat_t;
Thanks for help
I suspect the problem is with a.a[a.ja[i]]
, you should try verifying the values a.ja[i]
before using them to index a.a
.
It would be useful to know how a
is initialised, and also on which line the segfault occurs.
Malloc could be failing and returning null. a.ja[i] might not be between 0 and n. What is the ja array supposed to represent, anyway?
Our speculating isn't going to produce the answer. Running your program under a debugger will.
I suspect this is the line where the trouble is:
result.vec = malloc(a.n * sizeof *result.vec); for(i=0; i<a.n; i++) result.vec[i] = c.vec[i] * a.a[a.ja[i]];
The reason is that you are not malloc
ing for each result.vec[i]
..
Can you confirm this?
Edit:
Thanks Alok and Devel for informing me about my error...
What does sizeof *result.vec
return? Admittedly it looks confusing as if the precedence between sizeof
gets mixed with the *
...
Hope this helps, Best regards, Tom.
typedef struct {
int n;
int *vec;
} vec_t;
int main(int argc, char **argv) { vec_t result; int i; int size; result.n = 5; size = result.n * sizeof *result.vec; result.vec = malloc(size); for(i=0; i<result.n; i++) { result.vec[i] = i; } return i; }
I have to agree with Autopulated, this version of your code runs just fine, the only thing I left out in this refactoring is the a and c related stuff. I would check that a and c are being initialized properly.
精彩评论