I'm beginner in C and data structures, and getting a frustrating exception. I've compared with other doubly linked list codes but couldn't find the mistake.
While debuging the code, I get a warning about a read access violation from stdio.h and this is the troubled part:
return __stdio_common_vfprintf(_CRT_INTERNAL_LOCAL_PRINTF_OPTIONS, _Stream, _Format, _Locale, _ArgList);
Could you help me please?
struct Node* NewNode() {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node*));
new_node->next = NULL;
new_node->prev = NULL;
return new_node;
}
void InsertElement(char con, char name[51]) {
struct Node* new_node = NewNode();
strcpy(new_node->name,name);
if (head == NULL) {
head = new_node;
tail = head;
return;
}
if (con == 'H') {
head->prev = new_node;
new_node->next = head;
head = new_node;
}
else if (con == 'T') {
tail->next = new_node;
new_node->prev = tail;
tail = new_node;
}
}
void DisplayForward() {
if (head == NULL) {
printf("No Songs To Print\n*****\n");
return;
}
struct Node *temp = head;
while (temp != NULL) {
printf("%s\n", temp->name);
temp = temp->next;
}
printf("*****\n");
}
void DisplayReversed() {
if (head == NULL) {
printf("No Songs To Print\n*****\n");
return;
}
struct Node *temp = tail;
while (temp != NULL) {
printf("%s\n", temp->name);
temp = temp->prev;
}
printf("*****\n");
}
It seems the reason of the problem is the specified incorrect size of allocated memory in this declaration
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node*));
^^^^^^^^^^^^
You have to write
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
^^^^^^^^^^^^
That is you need to allocate memory for an object of the type struct Node
instead of allocating memory for a pointer of the type struct Node *
.
Pay attention to that the function InsertElement
is unsafe because the user can specify a wrong value for the parameter con
. In this case the function will produce a memory leak because the allocated node will not be inserted in the list and the address of the allocated memory for the node will be lost after exiting the function.
It is better to write two functions one of which will append a node to the beginning of the list and other - to the end of the list. In this case the parameter con will not be needed.