Vasyl Martyniv
Vasyl Martyniv

Reputation: 35

Segmentation fault on reallocating of memory

I need to make a program for bakery managment, I've done structures and three pointer arrays that must contain pointers for object of these structures. But i can't make function to add new bakery because it needs dynamic memory allocating. I've tried to do this but it throws Segmentation Fault on realloc. I would be grateful for any advice how to properly reallocate memory for these arrays to add element. Also feel free to make comments about other errors in the code, I'm just learning.

typedef struct BakeryType {
    char *name;
} BakeType;

typedef struct Bakerys {
    char *name;
    BakeType *type;
    char *photo;
    float weight;
    int portions;
    float price;
    char *description;
} Bakery;

Bakery *bakeryList[0];
BakeType *bakeTypeList[0];

void addBakery() {
    Bakery new;
    *bakeryList = realloc(*bakeryList, (sizeof(bakeryList)/ sizeof(Bakery))+ 1);//Segmentation Fault
    bakeryList[sizeof(bakeryList)/sizeof(Bakery)]=&new;
}


Upvotes: 0

Views: 125

Answers (1)

Willis Blackburn
Willis Blackburn

Reputation: 8204

bakeryList is a zero-element array of pointers to Bakery. It has room for zero pointers.

Yet later you set the first element of this array (*bakeryList which is the same as bakeryList[0]) to whatever comes back from realloc. So you're overwriting something, and it probably goes downhill from there.

I think you want bakeryList to just be a pointer to Bakery. That's how dynamically-allocated arrays work in C: you define a pointer to the first element and use pointer math (e.g., bakeryList[5] or *(bakeryList + 5)) to access other elements.

Another issue is your use of sizeof(bakeryList). sizeof is an operator that's evaluated by the compiler. It doesn't change at runtime. sizeof(bakeryList) / sizeof(Bakery) will evaluate to zero because you defined bakeryList as a zero-element array. You need another variable to keep track of how many elements are actually in the array at runtime.

Something like this would work:

int bakeryCount = 0;
Bakery *bakeryList = NULL;

void addBakery() {
    // Add one to the array.
    bakeryCount++;
    bakeryList = realloc(bakeryList, bakeryCount * sizeof (Bakery));
    // Create a pointer to the new element at the end of the array.
    Bakery *newBakery = bakeryList + bakeryCount - 1;
    // Set all the fields. Note that they will probably contain
    // garbage so you should set them all.
    newBakery->name = ...
}

Upvotes: 1

Related Questions