简体   繁体   中英

C realloc (dynamic arrays) - Access Violation

Starting out with dynamic arrays in C. I am getting an access violation when in the insertArray function (either in the realloc line or when trying to store the element (char) in the array.

Can't seem to work around it or get to the bottom of it. Thanks

Code:

#include <stdio.h>

typedef struct {
    char *array;
    size_t used;
    size_t size;
} Array;

Array elements;

void initArray(Array *a, size_t initialSize) {
    a->array = (char *)malloc(initialSize * sizeof(char));
    a->used = 0;
    a->size = initialSize;
}

void insertArray(Array *a, char element) {
    if (a->used == a->size) {
        a->size *= 2;
        a->array = (char *)realloc(a->array, a->size * sizeof(char));
    }
    a->array[a->used++] = element;
}

void popArray(Array *a) {
    a->used--;
}

void freeArray(Array *a) {
    free(a->array);
    a->array = NULL;
    a->used = a->size = 0;
}

char vars[15];

int main() {
    initArray(&elements, 2);
    printf("Enter 15 character String: ");
    scanf_s("%s", vars, 15);
    for (int i = 0; i < 15; i++) {
        insertArray(&elements, vars[i]);
    }
    freeArray(&elements);
}

I suspect the problem is caused by the missing #include <stdlib.h> .

See Do I cast the result of malloc? to understand why you should not cast the return value of malloc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM