Search code examples
cpointersstructure

Passing custom structure as argument causing segmentation fault


Working on implemeting graphs for a CS class project I declared these two structures

typedef struct person {
   char name[128];
   int age;
} Person;

typedef struct graph {

   int knots;
   int adjacencies[500][500];
   Person personList[500];
  
} Graph;

void insertPerson(Graph *g, Person p) {
   g->personList[knots] = p;
   (g->knots)++;
}

void writeAdjacencies(Graph g) {

  for(int i = 0; i < MAXDIM; i++) {
   for(int j = 0; j < MAXDIM; j++) {
     printf("%d ", g.adjacencies[i][j]);
    }
   printf("\n");
  }

}

Everything is fine except that when trying to create a menu function (reading inputs and then deciding whether to add new person or remove existing one, etc...) passing a graph pointer and then using it's pointed instance seems to be generating a segmentation fault.

void checkInput(int input, Graph *g) {

  int temp;
  char tempName[128];


  if(input == 1 ) {

    printf("\n  Name: ");
    scanf(" %[^\n]", tempName);
    printf("%s\n", tempName);

    Person p; 
    strcpy(p.name, tempName);

    /* takes graph pointer a person and just adds person to personList and increases knots
       it's working as intended
    */
    insertPerson(g, p); 

    /* Goes through each element in the matrix and prints it
       this is the one causing problems
    */
    writeAdjacencies(*g); 

  }
  
}

The code is working fine until the moment I pass *gas an argument - that is if I put the writeAdjacencies(*g) under a comment it does not cause any trouble.

I don't get what is the issue here? I feel as if I'm using pointers like I did so far throughout the year and it worked. Maybe I could be passing a null pointer? But I did inialize it in the main function I think.

main.c :


Graph graph;

for(int i = 0; i < MAXDIM; i++) {
 for(int j = 0; j < MAXDIM; j++) {
     g.adjacencies[i][j] = 0;
    }
 }
    
g.knots = 0;

checkInput(0, &g);

Any help is welcomed!

EDIT: included both missing functions


Solution

  • Ignoring the potential buffer overflows from your scanf code, your Graph structure is way too large for the stack (containing 250,000 integers). Use dynamic memory allocation instead. E.g.:

    typedef struct {
        int** adjacencies;
        int n;
    } Graph;
    
    void graph_init(Graph* g, int n) {
        g->n = n;
        g->adjacencies = malloc(n * sizeof(int*));
        for (int i = 0; i < n; ++i) {
            g->adjacencies[i] = malloc(n * sizeof(int));
        }
    }
    
    void graph_free(Graph* g) {
        for (int i = 0; i < g->n; ++i) {
            free(g->adjacencies[i]);
        }
        free(g->adjacencies);
        g->n = 0;
    }