Mallocation fault in malloc () function

1

I'm having a segmentation fault when I have implemented a dynamic array of pointers to be able to store the contents of a file line-by-line.

size_t file_mem_init(char ***ptr,FILE * file){

   size_t mem_size = getnline(file); // retorna a quantidades de linha no arquivo
   size_t x;

 if(mem_size == 0){
    puts("Arquivo vazio");
    exit(1);
  }
    *ptr = malloc(sizeof(**ptr)*mem_size);
    if(*ptr == NULL){
      perror("malloc in *ptr");
      exit(-1);
    }

    for(x = 0; x < mem_size && !feof(file);x++){
      // DEBUG 
      printf("%zu",x);

      // sizeofline(file) retorna a quantidade de caracteres de uma linha no arquivo. 
      *ptr[x] = malloc(sizeof(***ptr) * sizeofline(file)); <---- Falha de Segmentação
      if(*ptr[x]==NULL){
    printf("Na variavel *ptr[%zu]: %s",x,strerror(errno));
    exit(-1);
      }
      x++;
    }

    return mem_size;
}


void file_mem_free(char ***ptr,size_t len){
  while(len > 0)
    free(*ptr[--len]);

  free(*ptr);

}
    
asked by anonymous 19.09.2014 / 01:59

2 answers

2

I believe it is merely an operator precedence error. You allocate memory for the *ptr variable. But when using within the loop, you use *ptr[x] . This expression is interpreted as *(ptr[x]) , which I'm sure is not what you want. Use (*ptr)[x] to avoid the problem. Parentheses are required in this case.

Or even better: use an auxiliary variable:

char** lines = *ptr = malloc(...);

//...

char* line = lines[x] = malloc(...);

So there's no mistake.

    
20.09.2014 / 16:10
0

I suggest you simplify the statement

*ptr[x] = malloc(sizeof(***ptr) * sizeofline(file));

For example for

size_t tmp1 = sizeofline(file);
*ptr[x] = malloc(tmp1); // sizeof(***ptr) == 1

and now checks whether the error is in malloc() or sizeofline() .

    
19.09.2014 / 10:18