Search code examples
cpointersheaderdynamic-allocation

C - segmentation fault when accessing a pointer in header file


I'm programming in C, and have two files, func2.h:

#define NN 20

void network_construction(int **veins, int *num_veins){

        int i, j;


        for(i=0;i<NN;i++){
            num_veins[i] = NN/2;
        }


        veins = malloc(NN * sizeof(*veins));
        for (i = 0; i < NN; i++) { veins[i] = malloc(num_veins[i] * sizeof(*(veins[i]))); }
        for (i = 0; i < NN; i++) { for (j = 0; j<num_veins[i];j++) { veins[i][j] = -1; } }


    return;
    }

and main.c:

#include <stdio.h>
#include <stdlib.h>
#include "func2.h"

void main(){

    int num_veins[NN];
    int **veins;


    network_construction(veins, num_veins);

    printf("\n%d\n", num_veins[19]);
    printf("\n%d\n", veins[2][2]);

return;
}

num_veins[] gives the right number, 10, but when trying to access to any elements of veins, it gives segmentation fault. How can I use in main.c the values of veins that are filled in func2.h ? What am I doing wrong and why is this happening ?

EDIT:

These codes are a simplified version of bigger ones. In the answers there is a way to solve the problem, but it is not exactly what I want. What I need is to do the dynamic allocation in func2.h, so I don't want any calculation involving veins[][] in main.c before the call to network_construction().


Solution

  • The code below achieves what I wanted:

    void network_construction(int ***veins, int num_veins[]){
      int i,j;
    
      for(i=0;i<NN;i++){
        num_veins[i] = NN/2;
      }
    
      (*veins) = malloc((NN) * sizeof(**veins));
    
      for(i=0;i<NN;i++){
        (*veins)[i] = malloc(num_veins[i]*sizeof(*(*veins)[i]));
      }
    
      for (i = 0; i < NN; i++) { 
        for (j = 0; j < num_veins[i]; j++) {
          (*veins)[i][j] = -1; 
        }
      }
      return;}
    

    To call it in main():

    network_construction(&veins,num_veins);