Exception thrown: read access violation. **head** was 0xCCCCCCCC. occurred - c

I am writing a Linked list in C. This is my code. I cannot really see any logic error here but when printing in while loop, after the last node is printed it does not jump out of the loop but keep looping then give me this error "Exception thrown: read access violation. head was 0xCCCCCCCC. occurred" on the "head" pointer in the loop.
// ass0.c
#define _CRT_SECURE_NO_WARNINGS
#define _CRTDBG_MAP_ALLOC // need this to get the line identification
//_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF|_CRTDBG_LEAK_CHECK_DF); // in main, after local declarations
//NB must be in debug build
#include <crtdbg.h>
#include <stdio.h>
#include <string.h>
typedef enum { FALSE = 0, TRUE } BOOL;
struct Frame {
char* frameName;
struct Frame* pNext;
};
typedef struct {
char* animationName;
struct Frame* frames;
}Animation;
// Forward declarations
void InitAnimation(Animation*);
void InsertFrame(Animation*);
//void DeleteFrame(Animation*);
//void EditFrame(Animation*);
void ReportAnimation(Animation*);
//void CleanUp(Animation*);
int main(void)
{
char response;
BOOL RUNNING = TRUE;
Animation RG;
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
InitAnimation(&RG);
while (RUNNING)
{
printf("MENU\n 1. Insert a Frame at the front\n 2. Delete last Frame\n 3. Edit a Frame\n 4. Report the Animation\n 5. Quit\n");
scanf("%c", &response);
switch (response)
{
case '1':InsertFrame(&RG); break;
//case '2':DeleteFrame(&RG); break;
//case '3':EditFrame(&RG); break;
case '4':ReportAnimation(&RG); break;
//case '5':RUNNING = FALSE; CleanUp(&RG); break;
default:printf("Please enter a valid option\n");
}
}
return 0;
}
void InitAnimation(Animation* newAnimation) {
newAnimation = malloc(sizeof(Animation));
newAnimation->animationName = "Animation_1";
newAnimation->frames = NULL;
}
void InsertFrame(Animation* animation) {
printf("Insert a Frame in the Animation\n");
char fName[50];
printf("Please enter the Frame Name: ");
scanf("%s", fName);
struct Frame *newFrame;
newFrame = malloc(sizeof(struct Frame));
int nameSize = strlen(fName);
newFrame->frameName = malloc(nameSize + 1);
strcpy(newFrame->frameName, fName);
newFrame->pNext = 0;
//struct Frame* head;
if (animation->frames == NULL)
animation->frames = newFrame;
//head = animation->frames;
//head->pNext = NULL;
//head = animation->frames;
else {
//head = animation->frames;
newFrame->pNext = animation->frames;
animation->frames = newFrame;
/*while (head != NULL) {
newFrame->pNext = *head;
animation->frames = newFrame;
printf("%s", *head->frameName);
head = head->pNext;
}*/
//head = animation->frames;
printf("\n");
}
}
void ReportAnimation(Animation* animation) {
printf("Animation name is Animation_1\n");
printf("Report the Animation\n");
struct Frame* head = animation->frames;
//printf("%s\n", head->frameName);
while (head) {
printf("%s\n", head->frameName);
head = head->pNext;
}
//printf("%d", count);
}

At least the function InitAnimation does not make sense
void InitAnimation(Animation* newAnimation) {
newAnimation = malloc(sizeof(Animation));
newAnimation->animationName = "Animation_1";
newAnimation->frames = NULL;
}
and hence the program in whole is incorrect.
The original object
Animation RG;
//...
InitAnimation(&RG);
is not initialized. The parameter of the function is just overwritten.
The object of the type Animation is already created in main due to the definition
Animation RG;
You need only to initialize its data members.
Remove the statement with the malloc call
void InitAnimation(Animation* newAnimation) {
newAnimation->animationName = "Animation_1";
newAnimation->frames = NULL;
}
And in general you should allocate dynamically memory for the string that will be pointed to by the data member animationName.
The function cam look the following way
int InitAnimation( Animation *newAnimation, const char *name )
{
newAnimation->animationName = malloc( strlen( name ) + 1 );
int success = newAnimation->animationName !+ NULL;
if ( success )
{
strcpy( newAnimation->animationName, name );
newAnimation->frames = NULL;
}
return success;
}
and called like
Animation RG;
//...
InitAnimation(&RG, "Animation_1" );
Pay attention to that you need to include the header <stdlib.h> where the functions malloc and free are declared.

Related

Having Trouble printing a doubly linked list

I am currently having trouble trying to print my doubly linked list out. The problem is either in the getSongInfo function or in the printSongInfo function. I am very new to coding and all the help is greatly appreciated. I also don't know how to use the tail pointer when using a doubly linked list.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
#pragma warning(disable : 4996)
#pragma warning(disable : 6387)
#pragma once
//structs
typedef struct {
char* title;
char* artist;
int rating;
SongNode* next;
SongNode* prev;
}SongNode;
//Constants
#define kInfiniteLoop 1
#define kStringLength 30
//Prototypes
int getNum(void);
void eliminateEndOfLine(char* buffer);
void printSongInfo(SongNode* head);
SongNode* getSongInfo(SongNode** head, SongNode** tail, char title[], char artist[], int rating);
int main() {
char title[kStringLength];
char artist[kStringLength];
int rating = 0;
SongNode* head = NULL;
SongNode* tail = NULL;
printf("Enter Title, Artist and Rating\n");
printf("Enter'.' to get out of the loop and print list\n");
while (kInfiniteLoop) {
printf("Title: ");
fgets(title, kStringLength, stdin);
eliminateEndOfLine(title);
if (strcmp(title, ".") == 0) {
break;
}
printf("Artist: ");
fgets(artist, kStringLength, stdin);
eliminateEndOfLine(artist);
printf("Rating: ");
while (rating = getNum()) { // error check the rating this will check to make sure the rating is in the range 1-5.
if (rating < 1 || rating>5) {
printf("The number you have entered is invaild\n");
rating = 0;
printf("Rating: ");
continue;
}
break;
head=getSongInfo(&head, &tail, title, artist, rating);
printf("\n");
}
}
printSongInfo(head);
return 0;
}
/*===============================================================================================================*/
/*FUNCTION :getNum(void) */
/*PARAMETERS :void */
/*RETURNS :number */
/*DESCRIPTION:This function is the user input function to get a number rating */
/*===============================================================================================================*/
int getNum(void)
{/* the array is 121 bytes in size; we'll see in a later lecture how we can improve this code */
char record[121] = { 0 }; /* record stores the string */
int number = 0;
/* NOTE to student: indent and brace this function consistent with your others */
/* use fgets() to get a string from the keyboard */
fgets(record, 121, stdin);
/* extract the number from the string; sscanf() returns a number
* corresponding with the number of items it found in the string */
if (sscanf(record, "%d", &number) != 1)
{
/* if the user did not enter a number recognizable by
* the system, set number to -1 */
number = -1;
}
return number;
}
/*=======================================================================================================*/
/*FUCNTION :void eliminateEndOfLine */
/*PARAMETER :(char* buffer) */
/*RETURNS :void */
/*DESCRIPTION :This function takes a pointer to a string and looks through the string to find the */
/* newline.It takes the new line out of the string. */
/*=======================================================================================================*/
void eliminateEndOfLine(char* buffer)
{
char* target = strchr(buffer, '\n');
if (target != NULL)
{
*target = '\0';
}
}
SongNode* getSongInfo(SongNode** head, SongNode** tail, char title[], char artist[], int rating)
{
SongNode *newBlock = NULL;
newBlock = (SongNode*)malloc(sizeof(SongNode));
if (newBlock == NULL) {
printf("No memory to be Allocated\n");
return (*head);
}
newBlock->title=(char*)malloc(strlen(title) + 1);
if (newBlock->title == NULL) {
printf("No memory can be allocated for title\n");
return (*head);
}
newBlock->artist = (char*)malloc(strlen(artist) + 1);
if (newBlock->rating == NULL) {
printf("No memory can be alocated for artist\n");
return (*head);
}
newBlock->rating = (int)malloc(sizeof(int));
if (newBlock->rating == NULL) {
printf("No memory can be alllocated for rating \n");
return (*head);
}
strcpy(newBlock->title, title);
strcpy(newBlock->artist, artist);
newBlock->rating = rating;
newBlock->next = (*head);
newBlock->prev = NULL;
if ((*head) != NULL)
(*head)->prev = newBlock;
(*head) = newBlock;
return (*head);
}
void printSongInfo(SongNode* head) {
SongNode* ptr;
ptr = head;
printf("\n");
printf("%-35s %-35s %-35s\n", "Title", "Artist","Rating");
while (ptr != NULL) {
printf("%-35s %-35s %-35d\n", ptr->title, ptr->artist);
ptr = ptr->next;
}
}
You have a break statement in the while (rating = getnum()) loop that shouldn't be there. It will cause the loop to terminate before getting any song info.
Other problems:
newBlock->rating = (int)malloc(sizeof(int)); will leak memory, because you allocate some but never free it. Because rating is an int, memory does not need to be allocated for it. (Also, see Do I cast the result of malloc?).
getSongInfo should either return the new head, or update the current one, but not both.
Updating tail is similar to updating head, but does not need to be done all the time when inserting at the head (there's a condition that you'll need to check for).
You don't need #pragma once in a C source file. That should be in a header (and is only supported on some compilers).

Segmentation fault when using advance function

Hi am trying to create a generic list iterator that stores elements of integer or string.I am trying to test a case where it calls the IteratorG advance(IteratorG it, int n) function which takes in the list it and if n is a positive integer,it advances(moves) towards the first element by n times.If n is negative,it advances towards the last element in the list by n times.The elements are then copied to a newly created list lis and the list returned.If advancing by n times is not possible,the function returns NULL.
This is tested in test case 3 under the test cases below.
However,it is responding with a segmentation fault error and i tried using gdp to diagnose the problem and i suspect it is from the advance function at the line add(lis,&(tem->value));
This is the advance function:
IteratorG advance(IteratorG it, int n){
int zero;
zero=0;
IteratorG lis;
lis = malloc(sizeof (struct IteratorGRep));
assert (lis != NULL);
lis->numofit = 0;
lis->head = NULL;
lis->tail = NULL;
lis->curr = NULL;
Node *tem;
if ((tem = malloc(sizeof(Node))) == NULL) {
return 0;
}
if(n<0 && distanceFromStart(it)!=0 )
{
for(tem=it->curr;n!=zero;it->curr=it->curr->prev)
{
add(lis,&(tem->value));
zero++;
}
return lis;
}
if(n>0 && distanceToEnd(it)!=0)
{
for(tem=it->curr;n!=zero;it->curr=it->curr->next)
{
add(lis,&(tem->value));
zero++;
}
return lis;
}
//To be implemented
//move forward by n times
return NULL;
}
I am using a Linux environment and the errors are indicative from the results. The rest of the functions that are required to test this(test in test case 3 under the test code) should be working fine.Here is the code for the whole program:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include "iteratorG.h"
typedef struct Node {
void *value; // value of thee list item
struct Node *prev;
// pointer previous node in list
struct Node *next;
// pointer to next node in list
// implemented struct here ..
} Node;
typedef struct IteratorGRep {
int numofit; // count of items in list
Node *head; // first node in list
Node *curr; // current node in list
Node *tail; // last node in list
ElmCompareFp cmpElm;
ElmNewFp newElm;
ElmFreeFp freeElm;
// implemented struct here ..
} IteratorGRep;
/*
//Your functions below ....
*/
IteratorG newIterator(ElmCompareFp cmpFp, ElmNewFp newFp, ElmFreeFp freeFp){
IteratorG newit;
if ((newit = malloc(sizeof (struct IteratorGRep)))==NULL)
{
printf("Error...! \n");
}
//assert (newit != NULL);
newit->numofit = 0;
newit->head = NULL;
newit->tail = NULL;
newit->curr = NULL;
newit->cmpElm=cmpFp;
newit->newElm=newFp;
newit->freeElm=freeFp;
return newit;
// implemented function here and changed return value
}
int add(IteratorG it, void *vp){
Node *temp;
if ((temp = malloc(sizeof(Node))) == NULL) {
return 0;
}
Node *tempe;
if ((temp = malloc(sizeof(Node))) == NULL) {
return 0;
}
temp->value = it->newElm(vp);
//temp->next=NULL;
if(it->curr==NULL)
{
//temp->next=it->curr;
it->head=it->tail=temp;
it->curr=temp;
}
else
{
tempe=it->curr;
tempe->prev=temp;
temp->next=tempe;
it->curr=tempe;
it->curr=temp;
it->head=temp;
}
//it->tail=it->head=it->curr;
return 1;
}
int hasNext(IteratorG it){
if(it->curr->next==NULL)
{
return 0;
}
// check if theres next element/node
return 1;
}
int hasPrevious(IteratorG it){
if(it->curr->prev!=NULL)
{
return 1;
}
// check if theres previous element/node
return 0;
}
void *next(IteratorG it){
Node *tempo;
if(it->curr->next==NULL)
{
return NULL;
}
tempo=it->curr;
it->curr=it->curr->next;
// implemented function here
return tempo->value;
}
void *previous(IteratorG it){
Node *tempor;
tempor=it->curr;
if(tempor->prev==NULL)
{
return NULL;
}
tempor=it->curr->prev;
it->curr=it->curr->prev;
//tempor=it->curr;
// move to next node in list
return tempor->value;
}
int del(IteratorG it){
if(it->curr->prev!=NULL)
{
Node *temp_curr=it->curr;
Node *temp_prev=it->curr->prev->prev;
temp_curr->prev=temp_prev;
temp_prev->next=temp_curr;
return 1;
}// delete previous node from list
else
return 0;
}
int set(IteratorG it, void *vp){
if(it->curr->prev!=NULL)
{
it->curr->prev->value=vp;
return 1;
}
// change previous node value with new
return 0;
}
IteratorG advance(IteratorG it, int n){
int zero;
zero=0;
IteratorG lis;
lis = malloc(sizeof (struct IteratorGRep));
assert (lis != NULL);
lis->numofit = 0;
lis->head = NULL;
lis->tail = NULL;
lis->curr = NULL;
Node *tem;
if ((tem = malloc(sizeof(Node))) == NULL) {
return 0;
}
if(n<0 && distanceFromStart(it)!=0 )
{
for(tem=it->curr;n!=zero;it->curr=it->curr->prev)
{
add(lis,tem);
zero++;
}
return lis;
}
if(n>0 && distanceToEnd(it)!=0)
{
for(tem=it->curr;n!=zero;it->curr=it->curr->next)
{
add(lis,&(tem->value));
zero++;
}
return lis;
}
//To be implemented
//move forward by n times
return NULL;
}
void reverse(IteratorG it){
Node *curr = it->head;
Node *temp = NULL;
while(curr != NULL) {
temp = curr->next;
curr->next = curr->prev;
curr->prev = temp;
curr = temp;
}
temp = it->head;
it->head = it->tail;
it->tail = temp;// reverse elements of whole list
}
IteratorG find(IteratorG it, int (*fp) (void *vp) ){
// To be implemented
// Find elements of vp in list after current position and put in new list.return the list.
return NULL;
}
int distanceFromStart(IteratorG it){
Node *c=it->curr;
int count=0;
while(c->prev!=NULL)
{
c=c->prev;
count++;
}
return count;
// count number of elements from start of list to current position
}
int distanceToEnd(IteratorG it){
Node *cu=it->curr;
int count=0;
while(cu->next!=NULL)
{
cu=cu->next;
count++;
}
return count;
// count number of elements from end of list to current position
}
void reset(IteratorG it){
while(it->curr->prev!=NULL)
{
it->curr=it->curr->prev;
}
return;
// move current position to start of list
}
void freeIt(IteratorG it){
assert(it != NULL);
Node *curr, *prev;
curr = it->head;
while (curr != NULL) {
prev = curr;
curr = curr->next;
// free(prev->value);
free(prev);
}
free(it); // free items
}
This is the header file for the code:
#ifndef LISTITERATORG_H
#define LISTITERATORG_H
#include <stdio.h>
typedef struct IteratorGRep *IteratorG;
typedef int (*ElmCompareFp)(void const *e1, void const *e2);
typedef void *(*ElmNewFp)(void const *e1);
typedef void (*ElmFreeFp)(void *e1);
IteratorG newIterator(ElmCompareFp cmpFp, ElmNewFp newFp, ElmFreeFp freeFp);
int add(IteratorG it, void *vp);
int hasNext(IteratorG it);
int hasPrevious(IteratorG it);
void *next(IteratorG it);
void *previous(IteratorG it);
int del(IteratorG it);
int set(IteratorG it, void *vp);
IteratorG advance(IteratorG it, int n);
void reverse(IteratorG it);
IteratorG find(IteratorG it, int (*fp) (void *vp) );
int distanceFromStart(IteratorG it);
int distanceToEnd(IteratorG it);
void reset(IteratorG it);
void freeIt(IteratorG it);
#endif
One of the functions have yet to be implemented and is indicated in the code itself. But I guess that might not be the source of issue here.
EDIT:
heres the test case code. Theres no errors in the test case code just in the program above only :
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "iteratorG.h"
#include "positiveIntType.h"
#include "stringType.h"
#define MAXARRAY 5
/* Helper Functions Below */
/* Returns 1 if marks >= 50, 0 otherwise */
int passMarks(void *marks){
return (*((int *) marks) >= 50);
/* Easy to understand below ..
int *ip = (int *) marks;
if(*ip >= 50) { return 1; }
else { return 0; }
*/
}
/* Returns 1 if str starts with "jo" */
int prefixJo(void *str){
return (strncmp("jo", (char *) str, 2) == 0) ;
}
/* A function to print a string from a void pointer */
void prnStr(void *vp){
assert(vp != NULL);
printf(" %s", (char *) vp );
}
/* A function to print an integer from a void pointer */
void prnInt(void *vp){
assert(vp != NULL);
printf(" %d", *((int *) vp) );
}
/* Prints previous element using the given function 'fp'
examples: prnPrev(it1, prnInt); prnPrev(it2, prnStr);
*/
void prnPrev(IteratorG it, void (*fp) (void *p) ){
void *prevP = previous(it);
assert(prevP != NULL);
printf("> Previous value is: ");
fp(prevP);
printf("\n");
}
/* Prints next element using the given function 'fp'
examples: prnNext(it1, prnInt); prnNext(it2, prnStr);
*/
void prnNext(IteratorG it, void (*fp) (void *p) ){
void *nextP = next(it);
assert(nextP != NULL);
printf("> Next value is: ");
fp(nextP);
printf("\n");
}
/* Prints elements of 'it' from current to last position
using the given function 'fp'. The current position
of 'it' will change to the end of the list.
examples: prnIt(it1, prnInt); prnIt(it2, prnStr);
*/
void prnIt(IteratorG it, void (*fp) (void *p) ){
int count = 0;
while(hasNext(it)){
void *nextP = next(it);
count++;
if(count > 1) { printf(", "); }
fp(nextP);
}
printf("\n");
}
/* Few Tests Below */
void test1(){
printf("\n--==== Test-01 ====------\n");
IteratorG it1 = newIterator(positiveIntCompare, positiveIntNew, positiveIntFree);
int a[MAXARRAY] = { 25, 78, 6, 82 , 11};
for(int i=0; i<MAXARRAY; i++){
int result = add(it1 , &a[i]);
printf("> Inserting %d: %s \n", a[i], (result==1 ? "Success" : "Failed") );
}
freeIt(it1);
printf("--==== End of Test-01 ====------\n");
}
void test2(){
printf("\n--==== Test-02 ====------\n");
IteratorG it1 = newIterator(positiveIntCompare, positiveIntNew, positiveIntFree);
int a[MAXARRAY] = { 72, 14, 62, 8, 93};
for(int i=0; i<MAXARRAY; i++){
int result = add(it1 , &a[i]);
printf("> Inserting %d: %s \n", a[i], (result==1 ? "Success" : "Failed") );
}
prnNext(it1, prnInt);
prnNext(it1, prnInt);
prnPrev(it1, prnInt);
int newVal1 = 55;
int result1 = set(it1, &newVal1);
printf("> Set value: %d ; return val: %d \n", newVal1, result1 );
prnPrev(it1, prnInt);
freeIt(it1);
printf("--==== End of Test-02 ====------\n");
}
void test3(){
printf("\n--==== Test-03 ====------\n");
IteratorG it1 = newIterator(positiveIntCompare, positiveIntNew, positiveIntFree);
int a[MAXARRAY] = { 04, 54, 15, 12, 34};
for(int i=0; i<MAXARRAY; i++){
int result = add(it1 , &a[i]);
printf("> Inserting %d: %s \n", a[i], (result==1 ? "Success" : "Failed") );
}
reset(it1);
printf("> it1 (after reset): \n");
prnIt(it1, prnInt);
reset(it1);
IteratorG advIt1 = advance(it1, 4);
printf("> advance(it1, 4) returns: \n");
prnIt(advIt1, prnInt);
//IteratorG advIt2 = advance(it1, -3);
//printf("> advance(it1, -3) returns: \n");
//prnIt(advIt2, prnInt);
//printf("> In 'it1', ");
//prnPrev(it1, prnInt);
freeIt(it1);
//freeIt(advIt1);
//freeIt(advIt2);
printf("--==== End of Test-03 ====------\n");
}
int main(int argc, char *argv[])
{
test1();
test2();
test3();
return EXIT_SUCCESS;
}

Printing and Deleting queue in C

I'm trying to write a program that enqueue, dequeue, delete a chosen number and print the list. I have problems with the dequeue that i think is because of the menu part when you write a number, I've tried to fix it but the it removes the last number and not the first. The print shows the wrong number and when I tried to solve that problem I got the same problem as I had in dequeue. It's sometinhg wrong in delete but i cant figure it out.
I appreciate all the help i can get
edit:
I've changed it a lot and now everything else works except delete. I want delete to find the number i enter and delete it.
queue.c
#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
struct node
{
int info;
struct node *ptr;
int next;
}*first, *last, *temp, *first1;
void enq(int data);
void deq();
void empty();
void display();
void create();
void delete_queue();
int count = 0;
void main()
{
int no, ch;
printf("\n 1 - Enqueue");
printf("\n 2 - Dequeue");
printf("\n 3 - Delete");
printf("\n 4 - Display");
printf("\n 5 - Exit");
create();
while (1)
{
printf("\n Enter choice : ");
scanf_s("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf_s("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
printf("Enter data : ");
scanf_s("%d", &no);
delete_queue(no);
case 4:
display();
break;
case 5:
exit(0);
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
void create()
{
first = last = NULL;
}
void enq(int data)
{
if (last == NULL)
{
last = (struct node *)malloc(1 * sizeof(struct node));
last->ptr = NULL;
last->info = data;
first = last;
}
else
{
temp = (struct node *)malloc(1 * sizeof(struct node));
last->ptr = temp;
temp->info = data;
temp->ptr = NULL;
last = temp;
}
count++;
}
void display()
{
first1 = first;
if ((first1 == NULL) && (last == NULL))
{
printf("Queue is empty");
return;
}
while (first1 != last)
{
printf("%d ", first1->info);
first1 = first1->ptr;
}
if (first1 == last)
printf("%d", first1->info);
}
void deq()
{
first1 = first;
if (first1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (first1->ptr != NULL)
{
first1 = first1->ptr;
printf("\n Dequed value : %d", first->info);
free(first);
first = first1;
}
else
{
printf("\n Dequed value : %d", first->info);
free(first);
first = NULL;
last = NULL;
}
count--;
}
void delete_queue()
{
int retval = -1;
if (first)
{
struct node *temp = first;
first = first->next;
if (!first) { last = first; }
retval = temp->next;
free(temp);
}
return retval;
}
void empty()
{
if ((first == NULL) && (last == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
Let me start with a few points of advice about design and style:
I do not recommend this:
typedef struct node {
int data;
struct node *next;
} node;
you are typedefing struct node to node. while it is not illegal, it is confusing. I would recommend
typedef struct _node {
int data;
struct _node *next;
} node;
Additionally, I do not recommend use of global variable with static storage class to keep track of your queue, instead you should create a queue in your main. Use global variables only when you have compelling reasons to do so.
Do remember that when you get rid of your global variable, you will need to rewrite your enqueue dequeue delete etc... functions to take in a queue_c * as parameter (because it wont have access to queueref any more)
Now for the reason that your code is not working properly and #Weather Vane alluded to:
you have a big problem in your delete function.
int delete(int data)
{
int result = 0;
node *curr_ptr; //pointer just created and not initialized
node *prev_ptr; //not initialized
node *temp_ptr; //not initialized
while (curr_ptr != NULL)
//curr_ptr was just created, where is it pointing? fatal error here
{
//inside this block lets imagine curr_ptr is pointing to a valid
//node in the global queue
if (curr_ptr->data == data)
{
result = 1;
if (curr_ptr->next != NULL)
{
temp_ptr = curr_ptr;
//both pointers point to the same thing
destroy_node(temp_ptr);
//now you just destroyed both nodes
prev_ptr->next = curr_ptr->next;
//the first time this block runs prev_ptr is uninitialized
//so prev_ptr->next will most likely seg fault
//this happens for example if you call this function
//for the first time with a long queue
}
else
{
temp_ptr = curr_ptr;
queueref.last = prev_ptr;
prev_ptr->next = NULL;
destroy_node(temp_ptr);
//again you are destroying both curr_ptr and temp_ptr
}
}
curr_ptr = curr_ptr->next;
prev_ptr = prev_ptr->next;
return result;
}
}
Perhaps it would be better if you think edge cases very carefully and rethink some of the logic from scratch. (test edge cases as you go)

Issue Initializing Double Stacked linked lists in C

I am coding a data structure involving a set of two linked lists, stacked on top of each other. When trying to initialize the set in my test harness, I get a segmentation error. I've commented out all value setters to test to see if I could figure out the error myself, but I could not.
Prototype for init method:
Test Harness:
int
main( )
{
list the_list;
int used = 0;
int values[MAX_VALUES];
char input[LINE_LEN];
char command;
int argument;
int num_found;
bool result;
set_t lower;
set_t upper;
the_list->lower = lower;
the_list->upper = upper;
input[0] = '\0';
input[LINE_LEN-1] = '\0';
fgets( input, LINE_LEN, stdin );
while (*input != 'q') {
num_found = sscanf( input, "%c %d", &command, &argument );
if (num_found > 0) {
switch (command) {
case 'i':
printf ("Request to initialize the set\n");
if (num_found == 1) {
result = set_init( &the_list );
} else {
result = set_init( NULL );
}
printf ("Returned as %d\n", result);
break;
34,0-1 8%
Init method:
bool
set_init( list *the_list )
{
bool initialized = false;
if (the_list !=NULL ) {
/* We have space to initialize. */
the_list->lower->set_size = 0;
/* the_list->lower->head = NULL;
the_list->lower->tail = NULL;
the_list->lower->set_level = 1;
the_list->lower->ready = true;
the_list->upper->set_size = 0;
the_list->upper->head = NULL;
the_list->upper->tail = NULL;
the_list->upper->set_level = 2;
the_list->upper->ready = true;*/
initialized = true;
}
return initialized;
}
Also my struct definitions for my set, linked list, and node structs:
typedef struct _set_node_t {
test_type_t *data;
struct _set_node_t *next;
struct _set_node_t *below;
} set_node_t;
/* the set itself keeps track of the head and the tail of the linked list */
typedef struct {
int set_size;
bool ready;
set_node_t *head;
set_node_t *tail;
int set_level;
} set_t;
typedef struct {
set_t *lower;
set_t *upper;
}list;
The only thing that could be crashing here is this line:
the_list->lower->set_size = 0;
Either the_list or the_list->lower must be uninitialized or NULL or be pointing to invalid or inaccessible memory.
Edit: Yeah this line will crash because you don't initialize the_list.lower:
result = set_init( &the_list );
And this line will crash because you're passing NULL:
result = set_init( NULL );

Doubly linked list in C- delete node function

Doubly linked list nodes are created at the main function. Ender and header defined. Breaks at the delete node function- ender is null.
What's the best way to free the memory of the last and first input, i.e.: delete: 233,A and 888,F?
#include <stdafx.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
typedef struct record {
int idnumber;
char initial;
struct record *prevStudent;
struct record *nextStudent;
} STUDENT;
STUDENT *header = NULL; //pointer to the start of linked list
STUDENT *ender = NULL; //pointer to the end of the linked list
void Makenode(int x, char y);
void deletenode();
int main() {
Makenode(233, 'A');
Makenode(456, 'H');
Makenode(746, 'G');
Makenode(888, 'F');
deletenode();
fflush(stdin);
getchar();
return 0;
}
void Makenode(int x, char y) {
STUDENT *ptr;
ptr = (STUDENT *)malloc(sizeof(STUDENT));
if (ptr != NULL) {
ptr->idnumber = x;
ptr->initial = y;
ptr->nextStudent = header;
ptr->prevStudent = NULL;
if (header == NULL)
ender = ptr;
else
header->prevStudent = ptr;
header = ptr;
} else {
printf("Memory not allocated\n");
}
}
void deletenode() {
//delete the first and the last node of the linked list
STUDENT *p = header, *q = ender;
char c;
printf("Are you sure you want to delete Y/N:\n");
fflush(stdin); c=getchar();
while (c == 'Y' || c == 'y') {
ender=ender->nextStudent;
header=header->prevStudent;
free(p); free(q);
}
}
Your delete function leaves the linked list in an ilegal state. At all times (except temporarily inside your insert and delete functions), the following must be true:
If the header is null, the ender must also be null and the list is empty.
If a node p has a non-null link to p->next, then p->next->prev == p.
Likewise, if a node p has a non-null link to p->prev, then p->prev->next == p.
The header has no previous node; the ender has no next node.
These are the invariants of your linked list.
If you check your code for deleting:
void deletenode()
{
STUDENT *p = header, *q = ender;
ender=ender->nextStudent;
header=header->prevStudent;
free(p); free(q);
}
you can see that you just set the header and ender to NULL, because that's what ender->nextStudent and header->prevStudent are. But even reversing that won't help, because you must update the adjacent nodes' links.
Here are two functions - one for each task - that work:
void delete_first()
{
STUDENT *p = header;
if (p) {
if (p->nextStudent == NULL) {
header = ender = NULL;
} else {
p->nextStudent->prevStudent = NULL;
header = p->nextStudent;
}
free(p);
}
}
void delete_last()
{
STUDENT *p = ender;
if (p) {
if (p->prevStudent == NULL) {
header = ender = NULL;
} else {
p->prevStudent->nextStudent = NULL;
ender = p->prevStudent;
}
free(p);
}
}

Resources