1

I am trying to implement a dynamic array which must have the following struct:

typedef struct DArray{
    void **array;
    int capacity;
    int size;
    void (*display)(FILE *, void *); //function pointer to a non-generic display function
} DArray;

However, with the current behavior, the array doesn't seem to resize, and throws a segfault any time I try to access an index that's not zero. The constructor and insert function is as follows:

DArray *newDArray(void (*d)(FILE *,void *)){
    DArray *myDarray = malloc(sizeof(DArray));
    myDarray->array = malloc(sizeof(void *)); //size = 1 for now, otherwise multiply by array length
    myDarray->capacity = 1;
    myDarray->size = 0;
    myDarray->display = d;
    return myDarray;
}

void insertDArray(DArray *a,void *v){
    if (a->size < a->capacity)
        a->array[a->size] = v;
    else{
        void **newArray = malloc(sizeof(void *) * a->capacity * 2); //double size
        for (int i = 0; i <= a->size; i++)
            newArray[i] = a->array[i];  //clone old array
        a->capacity = a->capacity * 2;
        free(a->array);
        a->array = newArray;
    }
    a->size++;
}

I'm having trouble understanding my pointers here. I think what's happening is the pointer to a->array still points to the old, unresized array, but doing *a->array = newArray; does not work either. Can anyone shed some light on this?

Scott Sinischo
  • 111
  • 1
  • 1
  • 10

1 Answers1

3

You've got a buffer overrun caused by this loop. Should be i < a->size since if capacity is 5, you only expand it when size is also 5 and thus you'll be accessing the 6th element in the array.

for (int i = 0; i <= a->size; i++)

You're also not added the new value when you resize. Possibly change the logic of your code along the lines of...

if (a->size == a->capacity)
{
   /* resize array */
}
a->array[a->size++] = v;

...taking care to check the results of using malloc or realloc etc...

Chris Turner
  • 8,082
  • 1
  • 14
  • 18
  • Thanks, you're right. However, I still am getting a segfault when I try to access a->array[1] after inserting two elements. Is there anything in my insert code that could have caused this? – Scott Sinischo Mar 15 '17 at 14:25
  • @ScottSinischo Can you please create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve) and show us? Like how you use these functions? – Some programmer dude Mar 15 '17 at 14:33
  • It'd help if you included which line your debugger is saying the segfault is happening, but I noticed another problem with the code as-is and updated my answer. – Chris Turner Mar 15 '17 at 14:33