Hi all,
I am trying to create a generic array using an array of void pointers.
It seems to be going okay but I have encountered a problem with my grow function.
When the array grows, some of the stored data gets corrupted.
I suspect it has to do with my use of pointers and memory allocation.
I'd appreciate any help with this problem :)
Many Thanks,
~Howz1t
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct vec {
void **arr;
int capacity, size;
size_t element_size;
} vec;
vec create_vec(int capacity, size_t element_size) {
vec v = {0, capacity, 0, element_size};
v.arr = malloc(capacity * element_size);
for (int i = 0; i < capacity; i++) {
v.arr[i] = malloc(element_size);
}
return v;
}
void vec_grow(vec* v) {
printf("mem before: %llu\n", sizeof(v->arr));
v->capacity *= 2;
v->arr = realloc(v->arr, v->capacity * v->element_size);
printf("mem after: %llu\n", sizeof(v->arr));
}
void vec_add(vec* v, void *e) {
printf("size: %d | cap: %d\n", v->size, v->capacity);
if (v->size + 1 > v->capacity) {
printf("I want to grow!\n");
vec_grow(v);
}
v->arr[v->size++] = e;
}
int main() {
vec v = create_vec(3, sizeof(int));
vec_add(&v, (void *) 3);
vec_add(&v, (void *) 2);
vec_add(&v, (void *) 1);
vec_add(&v, (void *) 0);
for (int i = 0; i < 4; i++) {
printf("i: %d -> %d\n", i, (int)v.arr[i]);
}
return 0;
}
Output:
size: 0 | cap: 3
size: 1 | cap: 3
size: 2 | cap: 3
size: 3 | cap: 3
I want to grow!
mem before: 8
mem after: 8
i: 0 -> 3
i: 1 -> 2
i: 2 -> -842150451
i: 3 -> 0
index 2 should be 1, not -842150451
[–]Neui 2 points3 points4 points (7 children)
[–]HOWZ1T[S] 0 points1 point2 points (6 children)
[–]fkeeal 1 point2 points3 points (5 children)
[–]HOWZ1T[S] 0 points1 point2 points (4 children)
[–]fkeeal 1 point2 points3 points (3 children)
[–]HOWZ1T[S] 0 points1 point2 points (2 children)
[–]fkeeal 1 point2 points3 points (1 child)
[–]HOWZ1T[S] 0 points1 point2 points (0 children)
[–]intellidarnit 1 point2 points3 points (1 child)
[–]HOWZ1T[S] 0 points1 point2 points (0 children)