Search code examples
carraysmemory-managementdynamic-memory-allocation

Dynamic Memory Allocation for array of structs


So I've been working on a small project of mine and I got stuck at this phase. I keep getting Segfaults and I'm getting desperate. I have 2 structures

typedef struct {
    float time;
}Race;

typedef struct {
    char DriverName[50];
    int NoRaces;
    Race *races;
}Driver;

and I have to allocate memory for a single driver and then for an array of drivers after being given the number of races for each one. This is my code so far

Driver *allocDriver(int noRaces) {
    Driver *driver;
    driver = (Driver *)malloc(sizeof(Driver));
    driver->NoRaces = noRaces;
    driver->races = (Race *)malloc(sizeof(Race));       

    return driver;}


Driver **allocDrivers(int driversNo, int *driversRacesNo) {
    int i;
    Driver **drivers;
    drivers = (Driver **)malloc(driversNo * sizeof(Driver *));
    for(i = 0; i < driversNo; i++)
        drivers[i] = allocDriver(driversRacesNo[i]);

    return drivers;}

Solution

  • Though I'm not sure, for I have no idea how you call these from your main nor the content of the assignment; I suspect that you need change the following line;

    driver->races = (Race *)malloc(sizeof(Race));
    

    like:

    driver->races = (Race *)malloc(noRaces * sizeof(Race));
    

    For example, your code stores 5 as number of races, but does not allocate 5 memory spaces for struct Race (I think, this struct is for race results); for now, it just allocates one mem-width of struct Race.