Why do I segfault?

前端 未结 1 706
一向
一向 2021-01-25 23:20

Here is my code, I\'m getting a segmentation fault and I don\'t know why... I\'m creating a grid which n is its size, tab is an array which his type is

相关标签:
1条回答
  • 2021-01-26 00:16
    g->n = n;
    

    This is accessing an uninitalized value - invoking Undefined Behavior in your code. Move the line to after you allocate using malloc.

    Also g = malloc(sizeof(int) * (n*n)); is wrong you don't want grille* to point to a chunk which is allocated for int's. because in case there is not enough memory there will be undefined behavior acessing memory out of your allocation.

    g = malloc(sizeof(*g) * (n));
    

    As you have allocated the n*n locations for storing grille you should access them by indexing

          for (i = 0; i < n; i++)
          {
            // for some x
            g[i].tab[x].val = -1;
            g[i].tab[x].initial = 0;
          }
    

    Again g->tab[i].val = -1; this is wrong because of the same reason pointed earlier. You have to allocate memory to g[i].tab. Otherwise it's undefined behavior. You have to allocate memory for g[i].tab.

       g[i].tab = malloc(sizeof *g[i].tab * someSize);
    

    Also there is a flaw in your logic. First of all allocating nxn memory doesn't mean you have nxn grid. The method you followed will give you a contiguous chunk of nxn elements and that will not be of that use. (You can make a use of it but that's an overkill).

    The best thing you can do is a jagged array and it's example is shown here.

    Example code:-

    grille  *creer_grille(int n)
    {
      grille *g;
    
      g = malloc(sizeof *g * n);
      if( g == NULL){
        fprintf(stderr,"%s\n","Error in malloc");
        exit(1);
      }
    
      for (size_t i = 0; i < n; i++)
      {
        g[i].tab = malloc(sizeof *g[i].tab * n);
        if( g[i].tab == NULL){
            fprintf(stderr, "%s\n", "Error in malloc");
            exit(1);
        }
        g[i].n   = n;
        for(size_t j = 0; j < n; j++){
            g[i].tab[j].val = -1;
            g[i].tab[j].initial = 0;
        }
      }
      return g;
    }
    

    You have to free the dynamically allocated memory after you are done working with it. The free logic would be something like - you will first free the memory allocated in tab and then after all of those memory is freed, you will free memory allocated in g.

    0 讨论(0)
提交回复
热议问题