Skip to main content
2 de 2
se añadieron 225 caracteres en el cuerpo

Segmentation fault (core dumped) en C al asignar valor a variable de un struct

Me sale el error al intentar modificar la variable numContracts dentro de este struct:

typedef struct{
    tPartner *partnerList;
    int numPartners;
    tContract *contractList;
    int numContracts;
    tWorkspace workspaces[MAX_SPACES];
    int numSpaces;
} tCoworking;

Aquí es donde intento modificar numContracts:

void add_contract(tCoworking *cw, int partnerID, int spaceID, int month, int year){
    int contractPosition;
    
    assert(cw!=NULL);
    assert(partnerID>0);
    assert(spaceID>0);
    assert(month>0);
    assert(year>0);

    if(checkReservation(*cw, month, year, spaceID)==true){
        printf("ERROR: Workspace %d is reserved in period %d/%d\n", spaceID, month, year);
    }
    else if(find_partner(*cw, partnerID)==NULL){
        printf("ERROR: Partner %d does not appear in the list of partners\n", partnerID);
    }
    else if (checksMaxAnnex(*cw, partnerID, month, year)==true){
        printf("ERROR: Partner %d has the maximum of annexes allowed in period %d/%d\n", partnerID,month, year);
    }
    else{
        if(cw->numContracts==0){
            cw->contractList=(tContract*)malloc(sizeof(tContract));
            //cw->contractList=(tContract*)realloc(cw->contractList, (cw->numContracts +1)*sizeof(tContract));
            cw->contractList[cw->numContracts].partnerID=partnerID;
            cw->contractList[cw->numContracts].month=month;
            cw->contractList[cw->numContracts].year=year;
            cw->contractList[cw->numContracts].annex[0].idWorkspace=spaceID;
            cw->contractList[cw->numContracts].annex[0].monthlyPrice=100000;
            cw->contractList[cw->numContracts].numAnnex=1;
            cw->numContracts=1;
        }
        else{
            contractPosition=findContract(*cw, partnerID, month, year);
            if(contractPosition==-1){
                
            }
        }
    }
    
}

Por explicar el código un poco: Está este struct tCoworking que tiene dentro tres listas dinámicas: parnters, contrato y espacios de trabajo. La función de arriba intenta añadir un contrato para lo cual, antes revisa que el espacio de trabajo no esté cogido para la fecha especificada, que el partner aparece en la lista de partners y que el partner no tiene el máximo de espacios para esa fecha (3).

El error me sale cuanto intento añadir un contrato a una lista de contratos vacia (numContracts==0). Una vez añado todos los datos del contrato (id del partner, mes, año, etc.) tengo que hacer numContracts++ para llevar la cuenta de los contratos pero me da este error.

La variable se inicializa en esta función:

void init_coworking(tCoworking *cw){
    assert(cw!=NULL);
    cw->numPartners=0;
    cw->numContracts=0;
    cw->numSpaces=0;
}

En el foro en inglés me han dicho que el error debía estar en una parte del código que no estaba mostrando así que subo los tres archivos: main.c, coworking. y coworking.h en ese orden: main.c (dado por el profesor y no se puede modificar)

#include "coworking.h"

/**************************************************************************/
  int main (void)
/**************************************************************************/
{
  tCoworking c;



  /* section a */
  init_coworking (&c);
  
  /* section b */
  printf("\n******************************************************************\n");
  printf("Section B:");
  printf("\n******************************************************************\n");

  new_partner (&c, 11, "Anwar Sherman", 10);
  new_partner (&c, 16, "Isa Warner", 20);
  new_partner (&c, 24, "Reagan Sawyer", 8);
  new_partner (&c, 67, "Hashir Lloyd", 10);
  new_partner (&c, 88, "Amaya Kaye", 10);
  new_partner (&c, 11, "Rio Griffiths", 25);
  new_partner (&c, 91, "Barney McFarlane", 0);
  new_partner (&c, 94, "Terry Burt", 8); 
  
  /* section c */
  printf("\n******************************************************************\n");
  printf("Section C:");
  printf("\n******************************************************************\n");
  new_workspace (&c, 1, 2.15, tableFlex);
  new_workspace (&c, 2, 2.10, tableFlex);
  new_workspace (&c, 3, 1.80, tableFlex);
  new_workspace (&c, 4, 2.05, tableFix);
  new_workspace (&c, 5, 2.05, tableFix);
  new_workspace (&c, 6, 6.25, officeFix);
  new_workspace (&c, 1, 8.00, officeFix);
  new_workspace (&c, 8, 8.00, officeFix);

  /* section d */
  printf("\n******************************************************************\n");
  printf("Section D:");
  printf("\n******************************************************************\n");
  add_contract (&c, 11, 1, 10, 2020);
  add_contract (&c, 11, 2, 10, 2020);
  add_contract (&c, 11, 5, 10, 2020); 
  add_contract (&c, 88, 4, 10, 2020); 
  add_contract (&c, 88, 1, 11, 2020); 
  add_contract (&c, 24, 8, 10, 2020); 
  add_contract (&c, 88, 1, 10, 2020); 
  add_contract (&c, 55, 6, 12, 2020); 
  add_contract (&c, 11, 3, 10, 2020); 
  
  /*section e */
  printf("\n******************************************************************\n");
  printf("Section E:");
  printf("\n******************************************************************\n");

  print_workspaces(c,10,2020);

  return 0;
}

coworking.c (hecho enteramente por mí). El error debe estar en la línea

cw->numContracts++;

Ya que cuando la comento, el programa compila

#include "coworking.h"

tPartner *find_partner(tCoworking cw, int id){
    tPartner *partner;
    int i=0;
    
    partner=NULL;
    while(i<cw.numPartners && partner==NULL){
        if(cw.partnerList[i].id==id){
            partner=&(cw.partnerList[i]);
        }
        i++;
    }
    
    return partner;
}

tWorkspace *find_workspace(tCoworking cw, int id){
    tWorkspace *workspace;
    int i=0;
    
    workspace=NULL;
    while(i<cw.numSpaces && workspace==NULL){
        if(cw.workspaces[i].id==id){
            workspace=&(cw.workspaces[i]);
        }
        i++;
    }
    
    return workspace;
}

//Checks if there is a reservation in a specific date and workspace
bool checkReservation(tCoworking cw, int month, int year, int id){
    int i=0;
    int j=0;
    bool reserved=false;
    
    if(cw.numContracts>0){
        while(i<cw.contractList && reserved==false){
            if(cw.contractList[i].month==month && cw.contractList[i].year==year){
                while(j<cw.contractList[i].numAnnex && reserved ==false){
                    if(cw.contractList[i].annex[j].idWorkspace==id){
                        reserved=true;
                    }
                    j++;
                }
            }
            i++;
        }
    }
    return reserved;
}

//Checks if the partner has reached the mas of 3 annexes in one month
bool checksMaxAnnex (tCoworking cw, int id, int month, int year){
    int i=0;
    bool maxReached = false;
    
    if(cw.numContracts>0){
        while(i<cw.numContracts){
            if(cw.contractList[i].partnerID == id && cw.contractList[i].month == month && cw.contractList[i].year == year && cw.contractList[i].numAnnex==MAX_ANNEX){
                    maxReached==true;
            }
        }
    }
    
    return maxReached;
}

//Finds the position of a contract in the list given a partner and a date
int findContract(tCoworking cw, int id, int month, int year){
    int i=0;
    int position=-1;
    bool found=false;
    
    if(cw.numContracts>0){
        while(i<cw.numContracts && found == false){
            if(cw.contractList[i].partnerID == id && cw.contractList[i].month == month && cw.contractList[i].year == year){
                found=true;
                position=i;
            }
            i++;
        }
    }
    
    return position;
}

void init_coworking(tCoworking *cw){
    assert(cw!=NULL);
    cw->numPartners=0;
    cw->numContracts=0;
    cw->numSpaces=0;
}

void new_partner(tCoworking *cw, int partnerID, char name[MAX_NAME], int discount){
    assert(cw!=NULL);
    assert(partnerID>0);
    assert(discount>=0);
    
    if (find_partner(*cw, partnerID)!=NULL){
        printf("ERROR: Partner %d is already in the list of partners\n", partnerID);
    }
    else{
        if(cw->numPartners ==0){
            cw->partnerList=(tPartner*)malloc(sizeof(tPartner));
        }
        else{
            cw->partnerList=(tPartner*)realloc(cw->partnerList, (cw->numPartners+1)*sizeof(tPartner));
        }
        cw->partnerList[cw->numPartners].id=partnerID;
        strcpy(cw->partnerList[cw->numPartners].name, name);
        cw->partnerList[cw->numPartners].discount=discount;
        cw->numPartners++;
    }
}

void new_workspace(tCoworking *cw, int spaceID, double area, tFare fare){
    assert(cw!=NULL);
    assert(spaceID>0);
    assert(area>0);
    assert(fare>=0);
    assert(fare<4);
    
    if(find_workspace(*cw, spaceID)!=NULL){
        printf("ERROR: Workspace %d is already in the list of workspaces\n", spaceID);
    }
    else{
        cw->workspaces[cw->numSpaces].id=spaceID;
        cw->workspaces[cw->numSpaces].area=area;
        cw->workspaces[cw->numSpaces].fare=fare;
        cw->numSpaces++;
    }
}

void add_contract(tCoworking *cw, int partnerID, int spaceID, int month, int year){
    int contractPosition;
    
    assert(cw!=NULL);
    assert(partnerID>0);
    assert(spaceID>0);
    assert(month>0);
    assert(year>0);

    if(checkReservation(*cw, month, year, spaceID)==true){
        printf("ERROR: Workspace %d is reserved in period %d/%d\n", spaceID, month, year);
    }
    else if(find_partner(*cw, partnerID)==NULL){
        printf("ERROR: Partner %d does not appear in the list of partners\n", partnerID);
    }
    else if (checksMaxAnnex(*cw, partnerID, month, year)==true){
        printf("ERROR: Partner %d has the maximum of annexes allowed in period %d/%d\n", partnerID,month, year);
    }
    else{
        if(cw->numContracts==0){
            cw->contractList=(tContract*)malloc(sizeof(tContract));
            //cw->contractList=(tContract*)realloc(cw->contractList, (cw->numContracts +1)*sizeof(tContract));
            cw->contractList[cw->numContracts].partnerID=partnerID;
            cw->contractList[cw->numContracts].month=month;
            cw->contractList[cw->numContracts].year=year;
            cw->contractList[cw->numContracts].annex[0].idWorkspace=spaceID;
            cw->contractList[cw->numContracts].annex[0].monthlyPrice=100000;
            cw->contractList[cw->numContracts].numAnnex=1;
            cw->numContracts++;
            //printf("numContracts: %d\n", cw->numContracts);
        }
        else{
            contractPosition=findContract(*cw, partnerID, month, year);
            if(contractPosition==-1){
                
            }
        }
    }
    
}

void print_workspaces(tCoworking cw, int month, int year){
    int k=0;
    bool partnerFound=false;
    string name;
        
    printf("Workspaces reserved in %d/%d\n", month, year);
    for(int i=0; i<cw.numContracts; i++){
        partnerFound=false;
        k=0;
        if(cw.contractList[i].month==month && cw.contractList[i].year == year){
            while(k<cw.numPartners && partnerFound==false){
                if(cw.contractList[i].partnerID==cw.partnerList[k].id){
                    partnerFound=true;
                    
                    strcpy(name,cw.partnerList[k].name);
                }
            }
            printf("%s\n", name);
            for(int j=0; j<cw.contractList[i].numAnnex;j++){
                printf("Workspace number %d\n", cw.contractList[i].annex[j].idWorkspace);
            }
        }
    }


/*  for(int i=0; i<cw.numContracts;i++){
        printf("%d\n", cw.contractList[i].partnerID);
    }*/
}

Y coworking.h (hecho también por mí)

#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#define MAX_NAME 100
#define MAX_ANNEX 3
#define MAX_GENERAL 1000
#define MAX_SPACES 50
#define PTABLEFLEX 50.00
#define PTABLEFIX 80.00
#define POFFICEFIX 140.00

typedef char string[MAX_NAME];

typedef enum{
    tableFlex,
    tableFix,
    officeFix
} tFare;

typedef struct {
    int id;
    string name;
    int discount;
} tPartner;

typedef struct {
    int id;
    double area;
    tFare fare;
} tWorkspace;

typedef struct {
    int idWorkspace;
    double monthlyPrice;
} tContractAnnex;

typedef struct {
    int partnerID;
    int month;
    int year;
    tContractAnnex annex[MAX_ANNEX];
    int numAnnex;
} tContract;

typedef struct{
    tPartner *partnerList;
    int numPartners;
    tContract *contractList;
    int numContracts;
    tWorkspace workspaces[MAX_SPACES];
    int numSpaces;
} tCoworking;

tPartner *find_partner(tCoworking cw, int id);
tWorkspace *find_workspace(tCoworking cw, int id);
bool checkReservation(tCoworking cw, int month, int year, int id);
bool checksMaxAnnex (tCoworking cw, int id, int month, int year);
int findContract(tCoworking cw, int id, int month, int year);
void init_coworking(tCoworking *cw);
void new_partner(tCoworking *cw, int partnerID, char name[MAX_NAME], int discount);
void new_workspace(tCoworking *cw, int spaceID, double area, tFare fare);
void add_contract(tCoworking *cw, int partnerID, int spaceID, int month, int year);
void print_workspaces(tCoworking cw, int month, int year);

Siento mucho subir tanto código y gracias de antemano!

Edit: Como comenta @eferion hay un error en la línea

while(i<cw.contractList && reserved==false)

Que es lo que está causando el problema. Muchas gracias!!!