0

I'm trying to optimise my code and when I try to use a loop-invariant I get a segfault for a reason that I can't find.

This my function:

#include "kernel.h"

double baseline(unsigned n, double** a, double* b){

    unsigned i,j;
    double k;
    double s=0.0;

    for(j=0; j<n;j++)
        k = b[j];
        for(i=0;i<n; i++)
            s += a[j][i] * k;

    return s;
 }

My malloc looks ok:


        double** a = malloc(sizeof(double*)*n);
        for(i = 0; i < n; i++)
            a[i] = malloc(sizeof(double)*n);
        double* b = malloc(sizeof(double)*n);



and I fill my array like this:

//For tab a
void RempTabrandDouble(double** a, int n){

    for(int i=0;i<n; i++)
        for(int j=0;j<n;j++)
            a[i][j] = rand();   //On fera tjrs un random avec le meme seed

}
//For tab b
void RempTabAlea(double* b,int n){
    for(int i=0;i<n; i++)
        b[i] = rand();
}

Can you identify where is the seg problem please?

Thanks for your help

Justemax
  • 1
  • 1
  • How are the functions called? Please post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – MikeCAT Mar 22 '21 at 16:36
  • `a[j]` will be out-of-range (`j = N`) at `s += a[j][i] * k;` – MikeCAT Mar 22 '21 at 16:37
  • You're missing braces in your outer loop, so the two loops aren't nested. As MikeCAT points out, this results in `j` being `n` when the second loop is executed. Just add the missing braces. It's good practice to put braces around any loop with a multi-line body. – Tom Karzes Mar 22 '21 at 16:42
  • @TomKarzes Oh thank you, i don't khow i miss it! Thank you ! – Justemax Mar 22 '21 at 18:41
  • You need to learn [how to use a debugger](https://idownvotedbecau.se/nodebugging/). – Dour High Arch Mar 24 '21 at 16:20

0 Answers0