I have to work on linked lists and get a bad access error even before something happens in my main. I don't know what's wrong. I am relatively new to dynamic memory management. It would be nice if someone could take a look on the functions. The declaration was given by the professor, so we have to return a DoubleNote*. My code is below:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
double var;
struct node *next;
} DoubleNode;
DoubleNode* insertFirst(DoubleNode* head, double d){
DoubleNode* new_head;
new_head = (DoubleNode*)malloc(sizeof(DoubleNode));
if (new_head == NULL) {
printf("Error: Allocating memory for new node failed!");
exit(1);
}
new_head->var = d;
new_head->next = head;
head = new_head;
return head;
}
DoubleNode* inserLast(DoubleNode* head, double d){
DoubleNode* current = head;
while (current != NULL) {
current = current->next;
}
current->next = (DoubleNode*)malloc(sizeof(DoubleNode));
if (current->next == NULL) {
printf("Error: Allocating memory for new node failed!");
exit(1);
}
current->next->var = d;
current->next->next = NULL;
return head;
}
DoubleNode* inverseDoubleListCon(DoubleNode* head){
DoubleNode* current = head; // iteration variable starts on head of old list
DoubleNode* conHead = current; // Head of the new list
while (current != NULL) {
current = current->next; //iteration step
DoubleNode* newConHead = (DoubleNode*)malloc(sizeof(DoubleNode)); //allocating memory for new head
if (newConHead == NULL) {
printf("Error: Allocating memory for new node failed!");
exit(1);
}
newConHead = current; // new_head is the next variable in the old list
newConHead->next = conHead; //new head points to old head of the new list
conHead = newConHead; // new head is set
}
return conHead;
}
void printList(DoubleNode* head){
DoubleNode* current = head;
while (current != NULL) {
printf("%lf\n", current->var);
current = current->next;
}
}
int main(){
DoubleNode* head = NULL;
DoubleNode* inverseHead = NULL;
double d;
int i;
int sizeOfList;
printf("Insert amount of variables: \n");
scanf("%d", &sizeOfList);
for (i = 0; i < sizeOfList; i++) {
printf("Insert variable for node [%d]: \n", i);
scanf("%lf", &d);
head = insertFirst(head, d);
}
printList(head);
inverseHead = inverseDoubleListCon(head);
printList(inverseHead);
return 0;
}