title: Dynamic allocation of pointers don't look 'safe'
body: <p>Ok, I might be doing something wrong, but I can't figure it out and people I asked around me don't know either. Basically, I have defined a struct which is basically 8 integers (for now). I need, for the time being, 3 periodic square matrices of this struct of different sizes, for now simply set to have dimension N, 2N, and 4N. So, I set</p>
  
  <ul>
  <li>a pointer *ppl for the values</li>
  <li>a pointer **pop for the addresses with an extra border, for periodicity</li>
  <li>a pointer ***layer for the header, i.e. first element, address of each matrix</li>
  </ul>
  
  <p>The first thing I do is do allocate them with malloc. A simpler version of the program, with equal size (small) matrices worked fine. Now, It does not work well for the biggest matrix. When running on Linux using gcc, after setting the addresses, when initializing the matrix values (with N=10), on the element 28,22 the addresses stored on layer[0~2] change, according to gdb, resulting on a seg fault. Something like layer[1]: 0x606890 -> 0x1c -> 0x150000001c. Now, the same code running on a mac, compiled with llvm-gcc and debugged with lldb, do not show such behavior, but holds the same problem; some items that should have been initialized are not, leaving gibberish where should have been initial values.</p>
  
  <p>I tried to simplify the code to leave the essential information and put it here. The problem arises on the "initialize population" part, specially between the commented lines. I really don't know what is going on, and neither gdb nor lldb are helping me much anymore, since I kinda know where is the problem, but have know idea of what it is. I would really be thankful for any help!</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;tgmath.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;time.h&gt;
  #include &lt;stdbool.h&gt;
  
  #define N 10
  #define CH 6
  #define FREEDOM 10
  #define L_N 3
  #define D_MAX (FREEDOM-1)*(FREEDOM-1)*(CH)
  #define WS 100
  #define s_f 2 //layer scaling factor
  
  struct individual {
      int idx[CH];
      int row;
      int col;
  };
  
  struct gout {
      double idx[CH];
      int layer;
  };
  
  int main(void){
      int h,i,j,k,l;
      int tot_site=0,check;
      const int  M[L_N]={(N+2), N*s_f+2, N*s_f*s_f+2};
      static struct individual ***layer, **pop, *ppl;
      struct gout g_0[L_N];
      float tmp,*P, *pdf, Z[L_N];
      FILE *fp, *db;
  
      if ((fp = fopen( "tri-output.txt", "w")) == NULL) {
          printf("impossible to open file output.txt \n");
          exit(1);
      }
      else printf("output file open\n");
  
      if ((db = fopen( "tri-debug.txt", "w")) == NULL) {
          printf("impossible to open debug file  \n");
          exit(1);
      }
      else printf("debug file open\n");
  
      size_t pop_size=0;
      for (l=0; l&lt;L_N; l++) { pop_size += M[l]*M[l]; }
  
      //set program start, allocate memory
      pop=malloc(sizeof(struct individual*)*pop_size );
      ppl=malloc(sizeof(struct individual)*N*N*(1+s_f*s_f*(1+s_f*s_f)));              
      layer=malloc(sizeof(struct individual**)*L_N);
  
      srand(time(NULL));
  
      //NULL corners
      tot_site=0;
      for (i=0; i&lt;L_N; i++) {
          layer[i]=pop + tot_site; printf("pointer to layer %d: %p\n",i, layer[i]);
          *(layer[i])                 =NULL;    *(layer[i] + M[i]-1)=NULL;
          *(layer[i] +M[i]*(M[i]-1))  =NULL;    *(layer[i] + M[i]*(M[i]-1) + M[i]-1)=NULL;
          tot_site += M[i]*M[i];
      }
  
      //set inner lattice pointers
      check=0;
      for (k=0; k&lt;L_N; k++) {       
          for (i=1; i&lt;=N*((int)pow(s_f,k)); i++) {
              for (j=1; j&lt;=N*((int)pow(s_f,k)); j++) {
                  *(layer[k] + i*M[k]+j)=ppl + k*N*N*( ((int)(pow(s_f,2*k))-1)/(s_f*s_f-1) ) + N*((int)pow(s_f,k))*(i-1) + j-1; check++;
                  fprintf(db,"pop %d: %p -&gt; %p\n", check, (layer[k] + i*M[k]+j), *(layer[k] + i*M[k]+j));
              }
          }
      }
  
      printf("Inserting periodicity...\n");
      //insert periodicity, border pointers
      for (k=0; k&lt;L_N; k++) {
          for (i=1; i&lt;=N*((int)pow(s_f,k)); i++) {
              *(layer[k] + i)               =(ppl + k*N*N*( (int)(pow(s_f,2*k)-1)/(s_f*s_f-1) ) + N*(int)pow(s_f,k)*(N*(int)pow(s_f,k)-1) + i-1);
              *(layer[k] + M[k]*i)          =(ppl + k*N*N*( (int)(pow(s_f,2*k)-1)/(s_f*s_f-1) ) + N*(int)pow(s_f,k)*(i-1) + N*(int)pow(s_f,k)-1);
              *(layer[k] + M[k]*i + M[k]-1) =(ppl + k*N*N*( (int)(pow(s_f,2*k)-1)/(s_f*s_f-1) ) + N*(int)pow(s_f,k)*(i-1));            
              *(layer[k] + M[k]*(M[k]-1) +i)=(ppl + k*N*N*( (int)(pow(s_f,2*k)-1)/(s_f*s_f-1) ) + i-1);
          }
      }
  
      //setup probabilities
      printf("setting distribution...\n");
      P=malloc(sizeof(float)*FREEDOM*L_N);
      pdf=malloc(sizeof(float)*FREEDOM*L_N);
      for (l=0; l&lt;L_N; l++){
      Z[l]=0.0;
          for (k=0; k&lt;FREEDOM; k++){
             P[l*FREEDOM+k] = exp(-k*0.25*(l+1));
             Z[l]+=P[l*FREEDOM+k];
           }
            pdf[l*FREEDOM] = P[l*FREEDOM]/Z[l];
           for (k=1; k&lt;FREEDOM; k++){
              pdf[l*FREEDOM+k] = pdf[l*FREEDOM+k-1] + P[l*FREEDOM+k]/Z[l];
           }
      }
  
  
         fprintf(fp,"Initializing population:\n");
         fprintf(db,"__________l_i_j_k_____________\n");
  
      //initialize population
      check=0;
      for (l=0; l&lt;L_N; l++){
          fprintf(fp, "\n### Layer %d", l);
          for (k=0; k&lt;CH; k++) {
              g_0[l].idx[k]=0; 
          }
          g_0[l].layer=l; 
          for (i=1; i&lt;=N*(int)pow(s_f,l); i++) {
              fprintf(fp," \n");
              for (j=1; j&lt;=N*(int)pow(s_f,l); j++) {
                  fprintf(fp,"\t");
                  check++;
                  for (k=0; k&lt;CH; k++) {
                      //tmp=(float)rand()/(float)RAND_MAX;
                      //for (h=0; h&lt;FREEDOM; h++) {
                      //    if (tmp &lt; pdf[l*FREEDOM + h]) {
                              (*(layer[l] + i*M[l] + j))-&gt;idx[k]=1;//h;
                              fprintf(fp,"%1d",(*(layer[l] + i*M[l] + j))-&gt;idx[k]);
                              if (i &gt;27) fprintf(db,"ppl #%d %d,%d,%d,%d: %p -&gt; %p\n",check, l,i,j,k, (layer[l] + i*M[l] + j),*(layer[l] + i*M[l] + j));
                              g_0[l].idx[k]+= (*(layer[l] + M[l]*i + j))-&gt;idx[k];
                        //      break;
                         // }
                      //}
                  }
              (*(layer[l] + M[l]*i + j))-&gt;row=i;
              (*(layer[l] + M[l]*i + j))-&gt;col=j;
              }
          }
         fprintf(fp," \n ### \n");
      }
  
      fclose(fp);
      fclose(db);
      free(layer);
      free(pop);
      free(ppl);   
      free(P);
      free(pdf);
  
      return 0;
  }
  </code></pre>