Search code examples
clistvoid-pointersreallocsigabrt

Realloc in list implementation sends a SIGABRT signal on third call


typedef struct List {
    void **data;
    int dataSize;
    int count;
    int capacity;
} List;

List list_create(int dataSize) {
    List list;
    list.data = malloc(dataSize);
    list.dataSize = dataSize;
    list.count = 0;
    list.capacity = 1;
    return list;
}

void list_add(List *list, void *data) {
    if(list->count == list->capacity) {
        printf("INCREASING LIST...");
        void *temp = realloc(list->data, list->dataSize * list->capacity * 2);
        if(temp == NULL) {
            printf("FAILED\n");
            return;
        } else {
            printf("LIST INCREASED\n");
            list->data = temp;
        }
        list->dataSize = list->dataSize;
        list->count = list->count;
        list->capacity = list->capacity * 2;
    }

    list->data[list->count++] = data;
}

int main(int argc, char *argv[]) {
    List list = list_create(sizeof(int));
    int item1 = 5, item2 = 8, item3 = 3, item4 = 10, item5 = 15;
    list_add(&list, (void *)&item1);
    list_add(&list, (void *)&item2);
    list_add(&list, (void *)&item3);
    list_add(&list, (void *)&item4);
    list_add(&list, (void *)&item5);
    return 0;
}

Here I have my own implementation of a list, or dynamically sized array, in C. I'm testing it inside of my main function, but only the first four list_add calls are successful. On the fifth call -- which is the third time the list resizes the array backing it -- a SIGABRT signal gets sent out at the following line and the program is aborted.

void *temp = realloc(list->data, list->dataSize * list->capacity * 2);

I'm a bit stuck at the moment, and I'm still rather new to memory management and allocation in C.


Solution

  • I think the problem is that you are allocating your data array based on each element being of size dataSize, but later you use the data array by filling in with void * pointers. If you plan on using your array to hold pointers, you should size your array using sizeof(void *). This means you need to change two lines, the malloc call and the realloc call, replacing dataSize with sizeof(void *).

    If you did not intend to store pointers in the array, then you will need to change the way you assign to the array.