0

I'm trying to read a file containing wikipedia pages and turning them into a matrix of 0 and 1 depending on whether there is an arc between them. So that we call a function using this matrix to sort their [PageRank.][1] but it says segmentation fault. Any help would be much appreciated.


#include <stdlib.h>

#include <string.h>

#define SIZE 10000

int main(int argc, char
  const * argv[]) {
  int graphe[SIZE][SIZE] = {0};
  FILE * file = NULL;
  char chaine[SIZE] = "";//the line from fgets
  char * page = malloc(SIZE * sizeof(char));//an array with all the first pages of the file
  char ** tab = malloc(SIZE * SIZE * sizeof(char));//2D array containing all the pages
  file = fopen("wiki-zulu.txt", "r");
  if (file != NULL) {
    int i = 0, j = 0, cpt = 0;
    while (fgets(chaine, SIZE, file) != NULL) {
      char * token = strtok(chaine, "|");
      page[i] = * token;
      while (token != NULL) {
        tab[i][j] = * token;
        token = strtok(NULL, "|");
        j++;
        cpt++;
        i++;
      }
      for (int i = 0; i < cpt; i++) {
        for (int j = 0; j < cpt; j++) {
          for (int k = 0; k < cpt; k++) {
            if (tab[i][j] == page[k] && i != j) {//comparing all values in the 2D array with the array of pages
              graphe[i][k] = 1;//1 if there is a link between them
            }
            printf("%d\t", graphe[i][j]);
          }
        }
        printf("\n");
      }
      free(page);
      free(tab);
      fclose(file);
    }
  }
  return 0;
}```


  [1]: https://i.stack.imgur.com/eITFZ.png
Alex You
  • 1
  • 1
  • You need a graph database, not a matrix. – Cheatah Jan 29 '22 at 16:25
  • ```char ** tab = malloc(TAILLE * TAILLE * sizeof(char));``` I don't think this is the correct way to define a 2D matric in C and may very well be why you get a SEGFAULT. – Desperados Jan 29 '22 at 16:40

1 Answers1

0

Your problem is most likely the way you allocate the tab matrix. It is 1D array not a 2D one. And you cannot access it the way you are.

More standard, safer allocation of 2D matrix (you can change calloc with malloc):

// Allocate the first dimension and check for error
char **tab = (char **) calloc(SIZE, sizeof(char*));
if (!tab) {
   perror("calloc");
}

// Loop through the first dim to allocate the second one.
// Don't forget to free the allocated memory if something goes wrong
for (size_t i = 0; i < SIZE; ++i) {
   tab[i] = (char*) calloc(SIZE, sizeof(char));
   if (!tab[i]) {
      for (size_t j = i; j >= 0; --j) {
         free(tab[j]);
      }
      free(tab);
      perror("calloc");
   }
}
Desperados
  • 434
  • 5
  • 13