Search code examples
cpointersstructureallocation

Dynamic Alocation in c not working


I'm getting exit(1)(if there's some error in the allocation) every time i try to run the case 1. And i have no ideia why, can i get some help ?

#include <stdio.h>
#include <stdlib.h>

typedef struct hospede{             //guest
    int numreg;     //register num
    char nome[80];
    int acompanhante;   //n of ppl
    int dias;   //time to stay
    estado tabela;
}hospede;

typedef struct quarto{          //room
    int num;    //num do quarto
    char categoria;     //[S] ou [F]
    char status;        //[L] ou [O]
    estado stats;
    }quarto;

void alocaHospede(hospede **hosp, int tam);
void alocaQuartos(quarto **quar, int tam);
void geraQuartos(quarto *quar);
void checkIn(hospede *hosp, int tam);

int main()
{
    hospede *hpd = NULL;
    quarto *qrt = NULL;
    quarto quart;
    int qtd = 0;
    char op;
    int x;

    qrt = &quart;
    geraQuartos(qrt);
    do{
        printf("\n1-CheckIn\n>");
        scanf("%i", &x);
        fflush(stdin);
        switch(x){
        case 1:
            alocaHospede(&hpd, qtd+1);       
            checkIn(hpd, qtd);
        }
        printf("\nDeseja continuar? \n");
        scanf("%c", &op);
        fflush(stdin);
    }while(op!='n' && op!='N');

    return 0;
}
void checkIn(hospede *hosp, int tam){
    printf("\nwork\n");
}//checkIn
void alocaHospede(hospede **hosp, int tam){
    *hosp = (hospede*)realloc(*hosp, tam*sizeof(hospede));
    if(*hosp == NULL)
        exit(1);
}//aloca hospede

void alocaQuartos(quarto **quar, int tam){
if((*quar = (quarto *) realloc(*quar, tam * sizeof(quarto)))== NULL)
    exit(1);
}//alocaQuartos


void geraQuartos(quarto *quar){
    int i;
    for(i=0;i<15;i++,quar++){
        (*quar).num = i+1;
    }
}//geraQuartos

OBS:

I Removed some structures and unions that aren't being used yet to make the code shorter, also i'll do the allocation to the rooms as well, i think it's the same problem.


Solution

  • The for loop in geraQuartos is treating its argument as a pointer to an array of 15 quartos structures. But it's a pointer to just one structure, so it's writing outside the bounds of the object. This is causing undefined behavior, and in this case it's overwriting hpd so it's not NULL. This then causes realloc to fail because the first argument isn't NULL or a pointer that was previously returned by malloc.

    Change the declaration of quart to:

    quarto quart[15];
    

    and then do:

    geraQuartos(quart);