Access violation writing data to a doubly linked list - c

I got the following error:
0xC0000005: Access violation writing location 0x00000040.Which I assume means that the new contact is empty,when adding a new information to a doubly linked list using pointers.Ths is where I finish the function:
curr->next = newContact;
newContact->prev = curr;
newContact->next = NULL;
So I added the following if..else loop to check if curr is equal to the newContact and add it to the list.But that didn't work either..
if(curr-> newContact)
{
curr->next = newContact;
newContact->prev = NULL;
}
else
{
curr->next = newContact;
newContact->prev = curr;
newContact->next = NULL;
}
This is the complete function for reference:
int addContact(struct contact *theList)
{
struct contact *newContact, *curr;
// create the new structure
newContact = (struct contact *)malloc(sizeof(struct contact));
if( newContact == NULL )
{ // if true, then no memory left - oops
return(0);
}
// find the end of the list
curr = theList;
// scroll through the list
if(curr != NULL)
{
while( curr->next != NULL)
{
curr = curr->next;
}
}
// now have the last contact
// add the new one here.
printf("\nEnter a surname: ");
fflush(stdin);
gets(newContact->sname);
printf("\nEnter a first name: ");
gets(newContact->fname);
printf("\nEnter a phone: ");
gets(newContact->phone);
printf("\nEnter a company: ");
gets(newContact->company);
// need to hook the new contact to
// end of list
if(curr-> newContact)
{
curr->next = newContact;
newContact->prev = NULL;
}
else
{
curr->next = newContact;
newContact->prev = curr;
newContact->next = NULL;
}
return(1);
}//add
I cant see where I'm gone wrong in the check.Any ideas?Thanks

The access violation, and the address 0x00000040 in the error message, are telling you that you have not properly initialized curr which is a pointer to a structure of some sort. Odds are you declared it but never allocated memory for it or set it to point to a valid storage space.
I would bet money that curr is NULL and next is 0x40 bytes into the structure.
Expanding on your edited question... look at this block of code... what happens if curr is NULL ?? You're testing for the possibility, but then if it is NULL you don't do anything about it.
// find the end of the list
curr = theList;
// scroll through the list
if(curr != NULL)
{
while( curr->next != NULL)
{
curr = curr->next;
}
}

Related

Copy same elements from 2 ascending sorted linked lists to a new one

I'm writing a function that return a new list with elements contained in both two given ascending sorted lists, without any values repetition.
This code keeps given me LeakSanitazire: detected memory leaks, and i can't figure out what I'm missing.
intersezione.c
#include "intersezione.h"
#include <stdlib.h>
tlista intersezione(tlista lista1, tlista lista2){
tlista head = NULL;
tlista curr = NULL;
tlista tail_lista2;
while(lista1 != NULL){
tail_lista2 = lista2;
while(tail_lista2 != NULL){
if(lista1->valore == tail_lista2->valore){
if(head == NULL){
head = (tlista)malloc(sizeof(struct cella));
head->valore = lista1->valore;
head->next = NULL;
curr = head;
} else if(lista1->valore != curr->valore){
curr->next = (tlista)malloc(sizeof(struct cella));
curr = curr->next;
curr->valore = lista1->valore;
curr->next = NULL;
}
}
tail_lista2 = tail_lista2->next;
}
lista1 = lista1->next;
}
return head;
}
Here you can find the whole code.

I don't know why my linked list pointer isnt moving

I'm trying to write a piece of code that adds elements to a list.
typedef struct things {
int value;
struct things *next;
} something;
int main()
{
int input = 0;
something *head = NULL;
something *current = NULL;
current = head; //current points to head address
while(input != -1)
{
scanf("%d", &input);
while(current != NULL) //loop until current node returns NULL
{
current = current->next; //go to next node
}
current = malloc(sizeof(something)); //allocate memory for new node assuming current is NULL
current->value = input;
current->next = NULL; //next points to NULL
}
current=head; //current points back to head
while(current != NULL)
{
printf("%d -> ", current->value);
current = current->next;
}
puts("NULL");
return 0;
}
when i try to print through the list however, i get no output. So even if i input 1 2 3 4..etc the print function doesnt output anything
while(current != NULL)
{
printf("%d -> ", current->value);
current = current->next;
}
puts("NULL");
I'm expecting an output like 1 -> 2 -> 3 -> ... 9 -> NULL. I've just started learning about linked lists so any advice is appreciated.
You don't at any point update the value of head. Or point the last node in the list to the newly created one.
Check to see if head is set first and if not, populate it. Otherwise, find the last node of the list and add the new to as the "next" one from it like below.
if(head == NULL)
{
head = malloc(sizeof(something));
head->value = input;
head->next = NULL; //next points to NULL
}
else
{
current = head;
while(current->next != NULL) //loop until current node returns NULL
{
current = current->next; //go to next node
}
current->next = malloc(sizeof(something)); //allocate memory for new node assuming current is NULL
current->next->value = input;
current->next->next = NULL; //next points to NULL
}
Your current approach is not suited for single pointer.
Where allocating memory to current won't insert the node to list.
By just making current as pointer to pointer as below your approach will work.
int input = 0;
something *head = NULL;
something **current = NULL;
current = &head; //current points to head address
while(input != -1)
{
scanf("%d", &input);
while(*current != NULL) //loop until current node returns NULL
{
current = &(*current)->next; //go to next node
}
*current = malloc(sizeof(something)); //allocate memory for new node assuming current is NULL
(*current)->value = input;
(*current)->next = NULL; //next points to NULL
}
current=&head; //current points back to head
while(*current != NULL)
{
printf("%d -> ", (*current)->value);
current = &(*current)->next;
}
puts("NULL");

Can you help me understand why the below code on linked list gives me a segmentation fault error?

I am new to programming and took C to begin with, I was coding this linked list problem. What I thought I did is,
head pointer as global to access it from anywhere and set it to null initially
in the insert code, create new pointer of the same type and allocate memory and give it the inserted data. Point head pointer to this first inserted data current
for next insertions pass in the head and iterate over till the end and make the next of the last node point the current one and current to null
Similarly for display pass in the head and iterate till the end and print
What am I missing here can someone help me why am I getting segmentation fault error for the second input and how to correct it?
Should there be any changes to display function as well?
#include<stdio.h>
#include<stdlib.h>
void insert(int data_add);
void display();
struct list
{
int data;
struct list *next;
} *head = NULL;
int main()
{
int data_add,n;
while(1)
{
printf("\n\n1.Add\n2.Display\n3.Exit\n");
scanf("%d",&n);
switch(n)
{
case 1: printf("\nEnter the element to add ");
scanf("%d",&data_add);
insert(data_add);
break;
case 2: printf("The nos are: ");
display();
break;
case 3: exit(1);
break;
default: printf("\nOpen your eyes");
}
}
}
void insert(int add)
{
struct list *current,*temp;
current = (struct list*) malloc (sizeof(struct list));
current->data = add;
if(head == NULL)
{
head = current;
current->next = NULL;
}
else
{
for(temp = head; temp!=NULL;temp = temp->next);
temp->next = current;
current->next = NULL;
}
}
void display()
{
struct list *current;
current = head;
while(current!=NULL)
{
printf("%d",current->data);
current = current->next;
}
}
Think about this code:
for(temp = head; temp!=NULL;temp = temp->next);
temp->next = current;
So, your condition for ending the loop is temp != NULL Then, what is temp after the loop ran? NULL, of course!
Your stop-condition needs to be temp->next != NULL.
On a side note: It's time to learn using a debugger. With enough experience, you spot such things just by looking at code, but there are more complicated ways to fail as well ;) With a debugger, you would have found that issue immediately.
You are attempting to do:
NULL->next = current
Instead, in your for loop you should be checking for
temp->next != NULL
I think the problem is in the code below:
else{
for(temp = head; temp!=NULL;temp = temp->next);
temp->next = current;
current->next = NULL;
}
when the for loop breaks, temp becomes NULL so you shouldn't access temp->next
you can change your code as below:
void insert(int add)
{
struct list *current,*temp;
current = (struct list*) malloc (sizeof(struct list));
current->data = add;
if(head == NULL)
{
head = current;
current->next = NULL;
}
else
{
//for(temp = head; temp!=NULL;temp = temp->next);
temp = head;
while(true){
if(temp->next == NULL)
break;
temp = temp->next;
}
temp->next = current;
current->next = NULL;
}
}

Airline Reservation System using linked list

Im doing airline reservation system in c programming, using linked list. It reserves a seat, views the reservation, cancels the reservation. The program runs properly for the first time without adding any data.
But when i add data and want to delete it, it gives this error "Exception thrown at 0x0FFAFBB3 (ucrtbased.dll) in ConsoleApplication1.exe: 0xC0000005: Access violation writing location 0x0004B000."
For deleting data, im comparing the phone number data. And when it compares, it deletes the record. But instead it is giving error. Anyone identify the error area and provide suggestion??
Below is the code for making reservation and deleting a reservation.
void new_reservation()
{
curr = start;
if (start == NULL)
{
//Empty list
start = curr = (struct passenger *)malloc(sizeof(struct passenger));
dataentry();
curr->next = NULL;
printf("\n\t Reservation successful");
return;
}
//Reach end of list
while (curr->next)
curr = curr->next;
curr->next = (struct passenger *)malloc(sizeof(struct passenger));
curr = curr->next;
dataentry();
curr->next = NULL;
printf("\n\t Reservation successful");
printf("\n\t Saved to Reservation list");
}
void del()
{
struct passenger *temp; // assigning a temporary pointer to struct airplane
char str[20];
printf("Enter phone number:");
gets(str);
fflush(stdin);
curr = start;
while (curr)
{
if (strcmp(start->Phone, str) == 0)
{
temp = start;
start = start->next;
free(temp);
return;
}
if (strcmp(curr->next->Phone, str) == 0)
{
temp = curr->next;
curr->next = curr->next->next;
free(temp);
break;
}
else if (strcmp(curr->next->Phone, str) != 0)
{
printf("\n\n No reservations found!!");
break;
}
}
printf("\n\n Deletion successful!!");
}
if (strcmp(start->Phone, str) == 0){...}
if (strcmp(curr->next->Phone, str) == 0){...}
else if (strcmp(curr->next->Phone, str) != 0){...}
This method is too complicated, it is bound to run in to errors unless you carefully check the pointers and that pointer's next member. You can simplify this and make only one comparison. Just make sure to keep track of the node's position, if the node being deleted is the start or it is another node. Example:
void del()
{
char str[20];
struct passenger *walk = start;
if (!walk)
return;
printf("Enter phone number:");
scanf("%s", str);
struct passenger *previous = 0;
while (walk)
{
if (strcmp(walk->Phone, str) == 0)
{
struct passenger *next = walk->next;
free(walk);
if (previous == 0)
{
//deleting the first item
start = next;
}
else
{
//deleting an item in middle or end
previous->next = next;
}
return;
}
previous = walk;
walk = walk->next;
}
}
new_reservation is probably not causing any errors, but it too can be simplified. You only need to allocate once, then insert it either at the end, or assign it as start. Also you can use scanf to read a string.
void new_reservation()
{
//create new item
curr = malloc(sizeof(struct passenger));
curr->next = NULL;
//I don't know this part of your code...
dataentry();
if (start == NULL)
{
//Empty list
start = curr;
}
else
{
//find the end of the list
struct passenger *walk = start;
while (walk->next)
walk = walk->next;
walk->next = curr;
}
}

Linked list structures initialized in functions not being assigned properly

I'm sure this has been asked before, but I cannot find anything on this website or any other about it after searching for quite awhile.
I''m having trouble getting the values of structures that I'm creating and modifying in a function. The code looks something like:
struct node {
char name[35];
int employeeID;
struct node *next;
}
typedef struct node employee;
void insertInOrder(employee *head, employee *curr) {
if (head == NULL) {
*curr->next = *head;
*head = *curr;
} else {
if ((head->employeeID<curr->employeeID)&&(curr->employeeID <head->next->employeeID)) {
*curr->next = *head->next;
*head->next = *curr;
} else {
insertInOrder(head->next, curr);
}
}
}
void addEmployee(char name[], employee *head, employee *curr) {
int id;
scanf("%d", &id);
curr = malloc(sizeof(employee));
strcpy(curr->name, name);
curr->employeeID = id;
insertInOrder(head, curr);
}
int main(void) {
char name[35];
int quit = 1;
employee *head, *curr;
head = NULL;
printf("Enter data about the books: \n");
while (quit) {
scanf("%[^\n]%*c", title);
if (title[0] != '#') {
addBook(name, head, curr);
} else {
quit = 0;
}
}
During my debugging, my code iterates into all of my functions, but once I get back to main after adding all of the data I want, all of the variables are empty. I know it has something to do with the way I'm using or passing pointers, but when I look at the code I keep coming to the logical conclusion that what I have should do what I want. Please, someone point out where my algorithm is flawed.
addBook takes pointers of type Book but you are passing pointers of type Employee
Edit:
So, first you don't need to do things like *curr->next = *head. It should be curr->next = head.
Also, head->next can be null which is not being checked. Finally, head needs to always be pointed at the start of the list.
Edit 2:
Following code should work. head always points to the start of the list. In order to do that, we must pass the address of the head pointer. We need to do this because we will be modifying the address of head.
I've also cleaned up a few things.
void insertInOrder(employee **head, employee *curr) {
if (*head == NULL) {
// We are inserting the first element
*head = curr;
}
else if ((*head)->next == NULL) {
// This is the second element. We either insert it in front of head or before head.
if ((*head)->employeeID < curr->employeeID) {
(*head)->next = curr;
}
else {
curr->next = *head;
*head = curr;
(*head)->next = NULL;
}
}
else {
// We iterate through the list trying to find the best spot to insert curr.
employee *temp = *head;
while (temp->next != NULL) {
if ((temp->employeeID < curr->employeeID) && (curr->employeeID < temp->next->employeeID)) {
curr->next = temp->next;
temp->next = curr;
break;
}
temp = temp->next;
}
// curr has the greatest id so it is inserted at the end
if (temp->next == NULL)
temp->next = curr;
}
}
void addEmployee(char name[], employee **head) {
int id;
printf("Enter id\n");
scanf("%d", &id);
employee *curr = malloc(sizeof(employee));
strcpy(curr->name, name);
curr->employeeID = id;
curr->next = NULL;
insertInOrder(head, curr);
}
int main(void) {
int quit = 1;
employee *head = NULL;
char title[100];
printf("Enter data about the employees: \n");
while (quit) {
scanf("%s", title);
if (title[0] != '#')
addEmployee(title, &head);
else break;
}
return 0;
}
inside the function no need to use *head or *curr ..because -> is made up for pointers only instead directly use head->left & curr->next
thanks

Resources