Hello,
I'm currently trying to make a Vector in C. Most of functions seem to work but I'm getting a Segmentation Fault. Here is my code:
Code:
#include "Vector.h"
#include <stdio.h>
#include <stdlib.h>
#define NODES_AT_ONCE 1000
#define NAME_LENGTH 100
Node* orgHead;
Node* orgTail;
static Node* freeList = NULL;
Node* newNode( void* s, Node* next) {
Node * r = freeList; int i;
if ( freeList == NULL ) { /* then get space for some Nodes */
freeList = (Node*)calloc(NODES_AT_ONCE, sizeof(Node));
for(i = NODES_AT_ONCE - 1; i >= 0; i--) {
freeList[i].next = r;
r = &freeList[i];
} /* the Nodes are linked together as the freeList. */
}
freeList = r->next; strncpy(r->val, s, NAME_LENGTH); r->next = next;
return r; /* r points to the new Node which was removed from freeList */
}
void freeNode( Node* p ) { p->next = freeList; freeList = p; }
void newVector(Vector *pv) {
pv->head = pv->tail = (Node *)
pv->size = 0;
}
void add(Vector *pv, void* p) {
Node* v = (Node *)malloc(sizeof(Node));
v->val = p;
v->next = 0;
if (pv->size == 0) pv->head = pv->tail = v;
else pv->tail = pv->tail->next = v;
pv->size++;
}
void deleteAt(Vector *pv, int num) {
int i;
Node *v;
if (num == 0) pv->head = pv->head->next;
else {
v = pv->head;
for (i = 1; i < num; i++)
if (v->next != NULL) v = v->next;
if (v->next->next != NULL) v->next = v->next->next;
else v->next = NULL;
}
freeNode(v);
}
void insertAt(Vector *pv, int num, void* p) {
int i;
Node *v = (Node *)malloc(sizeof(Node));
v->val = p;
Node *curr;
if (num == 0) {
v->next = pv->head;
pv->head = v;
}
else if (num == pv->size-1) {
v->next = 0;
pv->tail = pv->tail->next = v;
}
else {
curr = pv->head;
for(i = 1; i < num; i++)
if (curr->next != NULL) curr = curr->next;
v->next = curr->next;
curr->next = v;
}
}
void* hasMore(Vector *pv) {
if (pv->head->next != NULL) return (void *)1;
else return 0;
}
void* next(Vector *pv) {
void* value = pv->head->val;
pv->head = pv->head->next;
return value;
}
void reset(Vector *pv) {
pv->head = orgHead;
}
main() {
Vector v;
newVector( &v ); //initializes v to be empty
add(&v, "Mom");
add(&v, "Dad");
add(&v, "dog");
add(&v, "Bro");
add(&v, "Sis");
deleteAt(&v, 2); // goodbye dog
insertAt(&v, 0, "Hi");
while ( hasMore( &v ) )
printf("%s ", (char *)next( &v ));
putchar('\n');
reset( &v );
while ( hasMore( &v ) )
printf("%s ", (char *)next( &v ));
putchar('\n');
}
What this does is it prints out Hi Mom and then gives a Segmentation Fault. I ran it through the gdb debugger and it said it was receiving the Segmentation Fault at the bolded line in the hasMore function. Any help would be appreciated!