Segmentation failure in malloc() function

Asked

Viewed 352 times

1

I am having a segmentation fault error when I have imploded a dynamical array of pointers to be able to store the contents of a row-by-row file.

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);

}
  • On which line is the error? Have you tried running in a debugger?

  • Just so I understand the idea, it has how to explain the logic you used to write this line: *ptr = malloc(sizeof(**ptr)*mem_size);?

  • According to gdb the segmentation failure is in malloc(). sizeofline() returns at least 1.

2 answers

2


I believe it to be merely an operator precedence error. You allocate memory for the variable *ptr. But when using inside 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 mandatory in this case.

Or better yet: use an auxiliary variable:

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

//...

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

So there’s no mistake.

0

I suggest you simplify the instruction

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

For example to

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

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

  • According to gdb the segmentation failure is in malloc(). sizeofline() returns at least 1.

  • Hmmm. Before the malloc() try printing the amount of bytes to allocate: printf("Tentando alocar %zu bytes.\n", tmp1);

  • allocating 19 to the *ptr[0] element allocating 1 to *ptr[1] allocating 1 to *ptr[2] allocating 1 to *ptr[3]zsh: Segmentation fault . /a. out main. c

  • The current code is here: https://github.com/tunixbsd/bugproof

Browser other questions tagged

You are not signed in. Login or sign up in order to post.