Problems with Realloc

2

Good afternoon, I'm having trouble creating a program that will increase the size of a designated list structure, similar to an array, whenever the occupancy rate of this list is more than 80% filled, I would like to increase it 2 times the size, using realloc, my problem is that I can not get more than 30 elements from the list, if in the while is i < 30 or another higher number starts to go wrong (Segmentation fault) I would like to know why, thank you.

#include "buffer.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

Buff init_buff() {
  int i = 0;
  Buff x = malloc(sizeof(struct buff));
  x - > size = 1;
  x - > used = 0;
  x - > lis = malloc(sizeof(struct lista));
  while (i < 10) {
    if (i % 2 == 0) x = load_buffer(x, "par");
    else x = load_buffer(x, "impar");
    i++;
  }
  return x;
}

Buff load_buffer(Buff x, char * l) {
  float taxa_ocupacao = x - > used / x - > size;
  //primeiro caso

  if (taxa_ocupacao > 0.8 || taxa_ocupacao == 0) {
    x - > lis = realloc(x - > lis, x - > size * 2 * (sizeof(struct lista)));
    x - > size *= 2;
  }

  x - > lis[x - > used].phrase = l;
  x - > used++;
  return x;
}
    
asked by anonymous 14.05.2018 / 19:54

1 answer

1

The error that is occurring is probably out of memory.

As each iteration of looping you allocate double the memory, after 30 iterations the realloc will try to allocate more than 2 30 ( > 1.073.741.824 ) " struct lista " s.

Assuming struct list has only 1 64-bit pointer, gives more than 8Gb of memory!

To check if it is a memory out of memory error, test whether the pointer returned by realloc is valid:

...
x->lis = realloc(x->lis, x->size*2*(sizeof (struct lista)));
// AQUI!
if (x->lis == NULL) {
  printf("Sem memória!");
  exit(1);
}
x->size*=2;
...
    
14.05.2018 / 21:20