I am trying to implement a linked list using malloc
. My linked list is just called a Vector
because I figured it made sense to mimic C++
.
So on my first TODO in initVector
is where I figured I screwed up.
I didn't have malloc()
called to add the Vector
passed through. That did not work. I even tried right after declaring the struct Vector
a to be:
struct Vector a = malloc(sizeof(struct Vector));
However that did not work either. What do I need to do to properly allocate memory for my LinkedList?
My second TODO states where the segfault occurs.
#include <stdio.h>
#include <stdlib.h>
// https://stackoverflow.com/questions/3536153/c-dynamically-growing-Vector
// https://stackoverflow.com/questions/314401/how-to-read-a-line-from-the-console-in-c
struct Vector {
char *index;
struct Vector *next;
size_t used;
size_t size;
};
void initVector(struct Vector *a, size_t initialSize) {
a = malloc(initialSize * sizeof(struct Vector)); //TODO: --1-- this i am just trying. i don't know how to do this because my free function is not working
a->index = malloc(initialSize * sizeof(char));
a->next = malloc(sizeof(struct Vector));
a->used = 0;
a->size = initialSize;
}
void insertVector(struct Vector *a, char *element) {
if (a->used == a->size) {
a->size *= 2;
a = realloc(a, a->size * sizeof(struct Vector));
}
a->used++;
a->index = element;
} // Adds an element to the index. If the allocated size is at the cap, it reallocates the current amount multiplied by two
void freeVector(struct Vector *a) {
free(a); //TODO: --1-- code segfaults here
a = NULL;
a->used = a->size = 0;
}
int main(int argc, char* argv[]) {
struct Vector a;
char *st = argv[1];
initVector(&a, 5); // initially 5 elements
insertVector(&a, st);
printf("%s\n", a.index);
freeVector(&a);
return 0;
}