Problems with the Realloc

Asked

Viewed 150 times

2

Good afternoon, I’m having difficulty creating a program that increases the size of a structure called list , similar to an array, whenever the occupancy rate of this list is more than 80% filled so I would like to increase the size 2 times , using realloc , my problem is that I can’t see more than 30 elements of the list , if no 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;
}
  • Good afternoon! Post the code itself instead of an image. So we can take the code and test to better help :)

1 answer

2

Probably the error that is occurring is lack of memory.

As with every iteration of looping you allocate double memory, after 30 iterations the realloc will attempt to allocate more than 230 (> 1.073.741.824) "struct lista"s.

Supposing struct list has only 1 64 bit pointer, gives more than 8Gb from memory!

To check if it is a memory fault, test if 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;
...

Browser other questions tagged

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