Using free for DLL Structure
Hi,
I'm not unfamiliar with programming, but I'm more comfortable with OOP languages like Java or C#. The last time I programmed in C was probably 2 1/2 years ago. So, I have some questions with regards to using the free function when dynamically allocating memory.
My issue is that I am getting a segmentation fault, which I'm pretty sure is because I am either using a pointer or memory incorrectly. However, I've been trying to figure out what is wrong, but I haven't found anything.
I'm compiling the program running: gcc -Wall -g -o dll dll.c, but I'm not getting any warnings or compile errors, which is leading me to believe it is within my code.
Here are the (I believe pertinent) items, which is implementing a Double Linked List.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//Double linked list structure
typedef struct Node
{
long int x;
char *a;
char *b;
char *c;
float num;
struct Node *next;
struct Node *prev;
} DLLNode;
//Implementation of adding to list
void InsertDataIntoList(DLLNode *node, long int _i, char *_a, char *_b, char *_c, float _num)
{
//Since the start of the list is passed in, iterate through the list until the end of list
while(node->next!=NULL) { node = node->next; }
//Allocate memory for the new node
node->next = malloc(sizeof(DLLNode));
(node->next)->prev = node; //Set up pointers for previous
node = node->next;
node->x = _i;
node->a = _a;
node->b = _b;
node->c = _c; //Put in data for the node
node->num = _num;
node->next = NULL; //The next node is null until values are put into it
}
//Freeing of the nodes
void DeleteAllNodes(DLLNode *node)
{
//Delete nodes from left to right
DLLNode *temp = node->next;
free(node->c);
free(node->b);
free(node->a);
if (node->prev != NULL)
{
free(node->prev);
}
free(node);
DeleteAllNodes(temp);
}
//In my main program I create a starter node, and then pass it in to functions
int main(int argc, char *argv[])
{
DLLNode *start = malloc(sizeof(DLLNode));
long int _i = 1234567;
char *_a = strdup("Hello");
char *_b = strdup("Its");
char *_c = strdup("Me");
float _num = 3.40;
InsertDataIntoList(start, _i, _a, _b, _c, _num);
DeleteAllNodes(start);
return 0;
}
Any help is appreciated.