aarelovich
aarelovich

Reputation: 5556

C: Segmentation fault when initializing pointers withtin structure

I've created a dynamic int array. I have tested it and it works fine. Now what I want to do is create a structure that uses two pointers to dynamic int arrays.

The DualBuffer definition is done like so:

typedef struct {
   DynamicIntArray *active;
   DynamicIntArray *fixed;
} DualBuffer;

DynamicIntArray is defined like this:

typedef struct {
    int *data;
    unsigned int size;
    unsigned int used;
    unsigned int sizeIncrease;
} DynamicIntArray;

To initialize a DualBuffer I call on this function:

DualBuffer dbInitialize(unsigned int starting_size, unsigned int size_increse){
    DualBuffer db;
    diaInitializeArray(db.active,starting_size,size_increse);
    diaInitializeArray(db.fixed, starting_size,size_increse); 
    return db;
}

Which calls on the DynamicIntArray intialization function:

void diaInitializeArray(DynamicIntArray *a, unsigned int startingSize, unsigned int size_increase){
   a->data = (int *) malloc(startingSize * sizeof(int));
   a->used = 0;
   a->size = startingSize;
   if (size_increase == 0) size_increase = 10;
   a->sizeIncrease = size_increase;
}

The only line in my main is this:

DualBuffer db = dbInitialize(5,5);   

However this, generates a segmentation fault. And I don't understand what I'm doing wrong.

Upvotes: 1

Views: 33

Answers (1)

Eraklon
Eraklon

Reputation: 4288

You did not allocated space for active and fixed. You should do something like this in dbInitialize:

DualBuffer dbInitialize(unsigned int starting_size, unsigned int size_increse){
    DualBuffer db;
    db.active = malloc(sizeof(DynamicIntArray));
    db.fixed = malloc(sizeof(DynamicIntArray));
    diaInitializeArray(db.active,starting_size,size_increse);
    diaInitializeArray(db.fixed, starting_size,size_increse); 
    return db;
}

Upvotes: 1

Related Questions