0

I have a two arrays of structs. One inside a Binary Search Tree:

typedef struct Equipo {
    char nombre[50];
    char marcaMoto[30];
    int puntuaciones;
    struct Piloto pilotos[18];
    int pilotoLibre;
    struct nodo* izquierdo;
    struct nodo* derecho;
} Equipo;

typedef Equipo Arbol;

typedef struct Piloto {
    int dorsal;
    char inicialNombre[1];
    char apellido1[50];
    char nacionalidad[3];
    int puntuacion;
    struct Premio* premios[18];
    int premioLibre;
} Piloto;

void InsertarPilotoEquipo(Equipo* arbol, char nombre[], Piloto* p) {
    if (!arbol) {
        return 0;
    } 
    Equipo* equipo = ObtenerEquipo(arbol, nombre);

    if (equipo) {
        struct Piloto* pilotos[18];
        pilotos[equipo->pilotoLibre] = p;
        equipo->pilotoLibre++;
        equipo->puntuaciones += p->puntuacion;
        memcpy(equipo->pilotos, p, sizeof equipo->pilotos);
        return 1;
    } else {
        return 0;
    }
}

And inside a linked list:

typedef struct Premio {
    char nombre[50];
    int puntos;
} Premio;

int insertarGP(Piloto* piloto, char nombre[50], int puntos) {
  struct Premio* p = (Premio *) malloc(sizeof(Premio *));
  strncpy(p->nombre, nombre, 50);
  p->puntos = puntos;
  struct Premio* premios[18];
  premios[piloto->premioLibre] = p;
  piloto->premioLibre++;
  piloto->puntuacion += puntos;
  memcpy(piloto->premios, p, sizeof piloto->premios);

  return 1;
}

The operation is practically the same, but function InsertarPilotoEquipo works but function insertarGP does not. If I debug I get in line strncpy(p->nombre, nombre, 50); the error:

output: malloc.c:2379: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
make: *** [makefile:9: compile] Abortado (core dumped) [Núcleo vaciado a un archivo]

In the rest of the function I get:

malloc(): corrupted top size
make: *** [makefile:9: compile] Abortado (core dumped) [Núcleo vaciado a un archivo]

why is this happening? what solution Do you have?

UPDATE WITHOUT CASTING IN MALLOC

int insertarGP(Piloto* piloto, char nombre[50], int puntos) {
  struct Premio* p = malloc(sizeof(*p));
  strncpy(p->nombre, nombre, 50);
  p->puntos = puntos;
  struct Premio* premios[18];
  premios[piloto->premioLibre] = p;
  piloto->premioLibre++;
  piloto->puntuacion += puntos;
  memcpy(piloto->premios, p, sizeof piloto->premios);

  return 1;
}

1 Answers1

2

This line in insertarGP

  struct Premio* p = (Premio *) malloc(sizeof(Premio *));

is bad because buffer for only one pointer is allocated and it is used for structure that will be larger than size of one pointer in typical environment.

The line should be

  struct Premio* p = malloc(sizeof(Premio));

or

  struct Premio* p = malloc(sizeof(*p));

Also see this: c - Do I cast the result of malloc? - Stack Overflow

MikeCAT
  • 73,922
  • 11
  • 45
  • 70