/* Queues */
/* Linear Queues */
#include <stdio.h>
#define MAX 10
int queue[MAX];
int rear=-1;front=-1;
void insert(void);
int delete_element(void);
int peek(void);
void display(void);
int main(){
int option;
printf("\n\n ***** MAIN MENU *****");
printf("\n 1. Insert an element");
printf("\n 2. Delete an element");
printf("\n 3. Peek");
printf("\n 4. Display the queue");
printf("\n 5. EXIT");
printf("\n Enter your option : ");
scanf("%d", &option);
switch(option){
case 1:
insert();
break;
case 2:
int val;
val = delete_element();
if(val != -1)
printf("\n The number deleted is :%d", val);
break;
case 3:
val = peek();
if(val != -1)
printf("\n the first value in queue is: %d", val);
break;
case 4:
display();
break;
}while(option !=5);
return 0;
}
void insert(){
int num;
printf("\n Enter the number to be inserted in the queue : ");
scanf("%d", &num);
if (rear == MAX-1){
printf("Queue is full");
}
else if(front == -1 && rear == -1){
front = rear = 0; /* If queue is empty, set front and rear to 0 */
}
else{
rear++; /* Increment rear */
queue[rear] = num;
}
}
int delete_element(){
int val;
if(front == -1 || front>rear){
printf("Queue is empty");
return -1;
}
else{
val=queue[front];
front++;
if(front>rear){
front = rear = -1; /* Front > rear = queue empty */
}
return val; /* Return popped value */
}
}
int peek(){
if(front == -1 || front>rear){
printf("Queue is empty");
return -1;
}
else{
return queue[front];
}
}
void display(){
int i;
printf("\n");
if(front == -1 || front>rear){
printf("Queue is empty");
}
else{
for(i=front;i<=rear;i++){
printf("\t %d",&queue[i]);
}
}
}
Code gets stuck while I try to insert element "3".
I am following Data Structures using C book, so I am not sure they would write a broken code to the book, but this just boggled my mind. It is running for 4 minutes, without doing literally anything. Neither deleting, peeking, inserting, displaying everything gets stuck in a loop.
You have the code (abbreviated):
switch(option){
...
}while(option !=5);
Slightly reformatted it's the same as:
switch(option){
...
}
while(option !=5)
{
}
That is, your switch ends and then you have an infinite loop.
I'll guess you really wanted to do an do-while loop around the menu and switch:
do
{
// Print menu
// Get input
// Switch
} while (option != 5);
Related
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 100
int enqueue();
int dequeue();
int peek();
void display();
int main()
{
char name[max][80], data[80];
int front, rear, value;
int ch;
front = rear = -1;
printf("------------------------------\n");
printf("\tMenu");
printf("\n------------------------------");
printf("\n [1] ENQUEUE");
printf("\n [2] DEQUEUE");
printf("\n [3] PEEK");
printf("\n [4] DISPLAY");
printf("\n------------------------------\n");
while(1)
{
printf("Choice : ");
scanf("%d", &ch);
switch(ch)
{
case 1 : // insert
printf("\nEnter the Name : ");
scanf("%s",data);
value = enqueue(name, &rear, data);
if(value == -1 )
printf("\n QUEUE is Full \n");
else
printf("\n'%s' is inserted in QUEUE.\n\n",data);
break;
case 2 : // delete
value = dequeue(name, &front, &rear, data);
if( value == -1 )
printf("\n QUEUE is Empty \n");
else
printf("\n Deleted Name from QUEUE is : %s\n", data);
printf("\n");
break;
case 3:
value = peek(name, &front, &rear, data);
if(value != -1)
{
printf("\n The front is: %s", value);
}
break;
case 5 : exit(0);
default: printf("Invalid Choice \n");
}
}
return 0;
}
int enqueue(char name[max][80], int *rear, char data[80])
{
if(*rear == max -1)
return(-1);
else
{
*rear = *rear + 1;
strcpy(name[*rear], data);
return(1);
}
}
int dequeue(char name[max][80], int *front, int *rear, char data[80])
{
if(*front == *rear)
return(-1);
else
{
(*front)++;
strcpy(data, name[*front]);
return(1);
}
}
int peek(char name[max][80], int *front, int *rear, char data[80])
{
if(*front == -1 || *front > *rear)
{
printf(" QUEUE IS EMPTY\n");
return -1;
}
else
{
return data[*front];
}
}
My Peek operation has a problem it does not print the first element.
For example, the user input one name, and when the user selects the peek operation, the program should print the first element, but my program always prints QUEUE IS EMPTY even though my queue is not empty.
The peek operation should print the first element of the queue.
If you enqueue() then peek() the variable front is still -1 and it incorrectly says the queue is empty.
I suggest your treat front to rear as a half open interval with both initialized to 0, so it's empty if *front == *rear.
peek() need to populate data and return an integer (not data[*front] which is nonsense).
main() after peek() you need to print data not value.
Your prototypes are wrong. If you move the functions before main() then you can remove them.
int enqueue(char name[max][80], int *rear, const char data[80]) {
if(*rear + 1 == max)
return -1;
strcpy(name[*rear], data);
(*rear)++;
return 1;
}
int peek(char name[max][80], int *front, int *rear, char data[80]) {
if(*front == *rear) {
printf(" QUEUE IS EMPTY\n");
return -1;
}
strcpy(data, name[*front]);
return 1;
}
// ...
int main() {
char name[max][80], data[80];
int front = 0;
int rear = 0;
int value;
int ch;
printf("------------------------------\n");
printf("\tMenu");
printf("\n------------------------------");
printf("\n [1] ENQUEUE");
printf("\n [2] DEQUEUE");
printf("\n [3] PEEK");
printf("\n [4] DISPLAY");
printf("\n------------------------------\n");
while(1)
{
printf("Choice : ");
scanf("%d", &ch);
switch(ch) {
case 1 : // insert
printf("\nEnter the Name : ");
scanf("%s",data);
value = enqueue(name, &rear, data);
if(value == -1 )
printf("\n QUEUE is Full \n");
else
printf("\n'%s' is inserted in QUEUE.\n\n",data);
break;
case 2 : // delete
value = dequeue(name, &front, &rear, data);
if( value == -1 )
printf("\n QUEUE is Empty \n");
else
printf("\n Deleted Name from QUEUE is : %s\n", data);
printf("\n");
break;
case 3:
value = peek(name, &front, &rear, data);
if(value != -1)
{
printf("\n The front is: %s\n", data);
}
break;
case 5 : exit(0);
default: printf("Invalid Choice \n");
}
}
return 0;
}
example session:
------------------------------
Menu
------------------------------
[1] ENQUEUE
[2] DEQUEUE
[3] PEEK
[4] DISPLAY
------------------------------
Choice : 1
Enter the Name : test
'test' is inserted in QUEUE.
Choice : 3
The front is: test
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 100
char name[max][80], data[80];
int front = 0;
int rear = 0;
int enqueue();
int dequeue();
int peek();
void display();
int main() {
int value;
int ch;
printf("------------------------------\n");
printf("\tMenu");
printf("\n------------------------------");
printf("\n [1] ENQUEUE");
printf("\n [2] DEQUEUE");
printf("\n [3] PEEK");
printf("\n [4] DISPLAY");
printf("\n------------------------------\n");
while(1)
{
printf("Choice : ");
scanf("%d", &ch);
switch(ch) {
case 1 : // insert
printf("\nEnter the Name : ");
scanf("%s",data);
value = enqueue(name, &rear, data);
if(value == -1 )
printf("\n QUEUE is Full \n");
else
printf("\n'%s' is inserted in QUEUE.\n\n",data);
break;
case 2 : // delete
value = dequeue(name, &front, &rear, data);
if( value == -1 )
printf("\n QUEUE is Empty \n");
else
printf("\n Deleted Name from QUEUE is : %s\n", data);
printf("\n");
break;
case 3:
value = peek(name, &front, &rear, data);
if(value != -1)
{
printf("\n The front is: %s\n", data);
}
break;
case 4:
display();
break;
case 5 : exit(0);
default: printf("Invalid Choice \n");
}
}
return 0;
}
int enqueue(char name[max][80], int *rear, const char data[80]) {
if(*rear + 1 == max)
return -1;
strcpy(name[*rear], data);
(*rear)++;
return 1;
}
int dequeue(char name[max][80], int *front, int *rear, char data[80])
{
if(*front == *rear)
return -1;
strcpy(data, name[(*front)++]);
return 1;
}
int peek(char name[max][80], int *front, int *rear, char data[80]) {
if(*front == *rear) {
printf(" QUEUE IS EMPTY\n");
return -1;
}
strcpy(data, name[*front]);
return 1;
}
void display(char name[max][80], int *front, int *rear, char data[80])
{
if(*front == -1 || *front > *rear)
{
printf("\n QUEUE IS EMPTY");
}
else
{
for(int i = *front; i<= *rear; i++)
{
printf("\t %s",data[i]);
}
}
}
Student here.
I need to display all elements inside the queue, but my program ends whenever I click option number 4, For example, the user inputs four names, "Jennie, Lisa, Jisoo, Rose", when the user selects option number 4, the program should print all 4 names. Even though I only input one name and need to print it, the program just ends. How to fix this?
I provided similar advise on earlier questions:
Your prototypes are incorrect (either fix them or delete them and move the definitions before use). I removed the prototype of display() and moved the implementation before use.
As your prototypes are wrong your compiler doesn't complain when you call dislay() without arguments (yours requires 4 arguments).
As display() doesn't change name, front, or rear I suggest you make first one const, and the other two integers. data is not used so eliminate it.
display(): queue is empty if front and rear have the same value.
Eliminate the global variables in favor of local variables in main().
Here is your working program:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define max 100
char name[max][80], data[80];
int front = 0;
int rear = 0;
int enqueue();
int dequeue();
int peek();
void display(const char name[max][80], int front, int rear) {
if(front == rear) {
printf("\n QUEUE IS EMPTY");
return;
}
for(int i = front; i < rear; i++)
{
printf("\t %s", name[i]);
}
printf("\n");
}
int main() {
int value;
int ch;
printf("------------------------------\n");
printf("\tMenu");
printf("\n------------------------------");
printf("\n [1] ENQUEUE");
printf("\n [2] DEQUEUE");
printf("\n [3] PEEK");
printf("\n [4] DISPLAY");
printf("\n------------------------------\n");
while(1)
{
printf("Choice : ");
scanf("%d", &ch);
switch(ch) {
case 1 : // insert
printf("\nEnter the Name : ");
scanf("%s",data);
value = enqueue(name, &rear, data);
if(value == -1 )
printf("\n QUEUE is Full \n");
else
printf("\n'%s' is inserted in QUEUE.\n\n",data);
break;
case 2 : // delete
value = dequeue(name, &front, &rear, data);
if( value == -1 )
printf("\n QUEUE is Empty \n");
else
printf("\n Deleted Name from QUEUE is : %s\n", data);
printf("\n");
break;
case 3:
value = peek(name, &front, &rear, data);
if(value != -1)
{
printf("\n The front is: %s\n", data);
}
break;
case 4:
display(name, front, rear);
break;
case 5 : exit(0);
default: printf("Invalid Choice \n");
}
}
return 0;
}
int enqueue(char name[max][80], int *rear, const char data[80]) {
if(*rear + 1 == max)
return -1;
strcpy(name[*rear], data);
(*rear)++;
return 1;
}
int dequeue(char name[max][80], int *front, int *rear, char data[80])
{
if(*front == *rear)
return -1;
strcpy(data, name[(*front)++]);
return 1;
}
int peek(char name[max][80], int *front, int *rear, char data[80]) {
if(*front == *rear) {
printf(" QUEUE IS EMPTY\n");
return -1;
}
strcpy(data, name[*front]);
return 1;
}
and sample session:
------------------------------
Menu
------------------------------
[1] ENQUEUE
[2] DEQUEUE
[3] PEEK
[4] DISPLAY
------------------------------
Choice : 1
Enter the Name : test
'test' is inserted in QUEUE.
Choice : 1
Enter the Name : test2
'test2' is inserted in QUEUE.
Choice : 4
test test2
I am getting a "Function should return a value" error at the 91st line of the code in Turbo C++, please help me as I have to submit my project, I know that Turbo C++ is a very old compiler but that's what our University Teacher recommends so I cant do nothing in that
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
#include <stdio.h>
#include <conio.h>
struct stack
{
int element;
struct stack *next;
} * top;
void push(int);
int pop();
void display();
void main()
{
int num1, num2, choice;
while (1)
{
clrscr();
printf("Select a choice from the following:");
printf("\n[1] Push an element into the stack");
printf("\n[2] Pop out an element from the stack");
printf("\n[3] Display the stack elements");
printf("\n[4] Exit\n");
printf("\n\tYour choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
{
printf("\n\tEnter the element to be pushed into the stack: ");
scanf("%d", &num1);
push(num1);
break;
}
case 2:
{
num2 = pop();
printf("\n\t%d element popped out of the stack\n\t", num2);
getch();
break;
}
case 3:
{
display();
getch();
break;
}
case 4:
exit(1);
break;
default:
printf("\nInvalid choice !\n");
break;
}
}
}
void push(int value)
{
struct stack *ptr;
ptr = (struct stack *)malloc(sizeof(struct stack));
ptr->element = value;
ptr->next = top;
top = ptr;
return;
}
int pop()
{
if (top == NULL)
{
printf("\n\STACK is Empty.");
getch();
exit(1);
}
else
{
int temp = top->element;
top = top->next;
return (temp);
}
}
void display()
{
struct stack *ptr1 = NULL;
ptr1 = top;
printf("\nThe various stack elements are:\n");
while (ptr1 != NULL)
{
printf("%d\t", ptr1->element);
ptr1 = ptr1->next;
}
}
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
The compiler is complaining because you don’t have a return statement outside of the if statement. Even though you call exit in the if branch, syntactically speaking that’s just another function call; structurally, the compiler sees a pathway where you reach the closing } of the function body without a return statement.
You want to make sure the return is reachable outside the body of the if-else statement, and the best way to do it is take the else branch out of the statement entirely:
int pop( void )
{
int temp;
if ( !top )
{
fputs( "Stack is empty", stderr );
exit( 1 );
}
temp = top->element;
top = top->next;
return temp;
}
you can change your pop function as below ( assuming you are not storing -1 as an element in the stack)
int pop()
{
if (top == NULL)
{
printf("\n\STACK is Empty.");
getch();
return -1;// or other invalid value which indicates stack empty
}
else
{
int temp = top->element;
top = top->next;
return (temp);
}
}
and at the place you are calling modify as following
case 2:
{
num2 = pop();
if(num2 != -1) {
printf("\n\t%d element popped out of the stack\n\t", num2);
getch();
}else{
printf("Stack is Empty\n");
exit(1);
}
break;
}
I'm writing this code for an assignment and the functions are supposed to be generic and it's up to the user to decide whether to work with integers or strings.
Obviously I wrote specific functions for operations for both types.
The only problem left in the code is when I try to free int type allocated memory I get the following:
Exception thrown at 0x0F24904D (ucrtbased.dll) in ConsoleApplication7.exe: 0xC0000005: Access violation reading location 0x00000006.
I get this only when debugging but compiling without debugging will simply stop when I try to perform the operation and freeze for a few seconds before ending the program.
Here's the entire code:
Header:
#ifndef _HEADER_H
#define _HEADER_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
typedef enum { FALSE, TRUE } BOOL;
/* defining specific function names*/
typedef int(*compare_func)(void*, void*);
typedef void(*print_func)(void*);
typedef void(*free_func)(void*);
/* defining struct names and pointers*/
typedef struct set Set;
typedef struct set* PSet;
typedef struct list List;
typedef struct list* PList;
/* creating and initialzing a set*/
List* createSet(compare_func cmp_fnc, print_func prnt_fnc, free_func free_fnc);
/* finding the biggest value in the set*/
void* findMax(PList List);
/* finding the smallest value in the set*/
void* findMin(PList List);
/* finding an element in the set*/
BOOL findInSet(PList List, void* val);
/* function for finding the size of the list*/
int setSize(PList list);
/* inserting a new element.*/
BOOL addToSet(PList List, void *data);
/* deleting an element, pointered by todel*/
BOOL deleteFromSet(PList list, void *todel);
/* print the elements in the set */
void printAll(PList list);
/* deleting the entire set */
void deleteSet(PList list);
#endif
Implementation:
#include "Header.h"
struct set // Set struct for doubly-linked list
{
void* data;
struct set *next, *prev;
};
struct list // List struct
{
int ListSize;
Set *head;
Set *tail;
compare_func compare;
print_func print;
free_func free;
};
List* createSet(compare_func cmp_fnc, print_func prnt_fnc, free_func free_fnc) // Function for initializing and creating a set
{
PList LIST;
LIST = (PList)malloc(sizeof(List));
if (LIST == NULL)
{
printf("Error! Memory allocation failed.\n");
exit(1);
}
LIST->ListSize = 0;
LIST->head = NULL;
LIST->tail = NULL;
LIST->compare = cmp_fnc;
LIST->print = prnt_fnc;
LIST->free = free_fnc;
return LIST;
}
void* findMax(PList List) // Function for finding the biggest value in a set
{
if (List->head == NULL) // If the set is empty
return NULL;
PSet temp;
void* max = List->head->data;
temp = List->head;
while (temp)
{
if (List->compare(temp->data, max) == 1) // Finding the biggest value
max = temp->data;
temp = temp->next; // Moving to the next node
}
return max;
}
void* findMin(PList List) // Function for finding the smallest value in a set
{
if (List->head == NULL) // If the set is empty
return NULL;
PSet temp;
void* min = List->head->data;
temp = List->head;
while (temp)
{
if (List->compare(temp->data, min) == -1) // Finding the smallest value
min = temp->data;
temp = temp->next; // Moving to the next node
}
return min;
}
BOOL findInSet(PList List, void* val) // Function for checking whether a given character is in the set
{
if (List->head == NULL) // If the list is empty
return FALSE;
PSet temp;
temp = List->head;
while (temp)
{
if (List->compare(temp->data, val) == 0) // If the character exists
return TRUE;
temp = temp->next; // Moving to the next node
}
return FALSE;
}
int setSize(PList list)
{
return list->ListSize;
}
BOOL addToSet(PList List, void *data) // Function for adding an item to the set
{
PSet temp, CurrentNode;
CurrentNode = List->head;
temp = (PSet)malloc(sizeof(Set));
if (temp == NULL) // If the allocation failed return false
return FALSE;
temp->data = data; // Filling the temp with the data
temp->next = NULL;
temp->prev = NULL;
if (List->head == NULL) // If the list is empty
{
List->head = temp;
List->tail = temp;
List->ListSize++;
return TRUE;
}
else {
while (CurrentNode) // Loop for checking whether the inserted character exists in the list
{
if (List->compare(data, CurrentNode->data) == 0) return FALSE;
CurrentNode = CurrentNode->next;
}
List->tail->next = temp; // Adding the node to the list
temp->prev = List->tail;
List->tail = temp; // Updating the tail
List->ListSize++;
return TRUE;
}
}
BOOL deleteFromSet(PList list, void *todel) // Function for deleteing an item from a set
{
PSet nodeToDel;
if (list->head == NULL) // If the list is empty
return FALSE;
if (list->compare(todel, list->head->data) == 0) // If the node to be deleted is the head
{
nodeToDel = list->head;
list->head = list->head->next;
if (list->head != NULL)
list->head->prev = NULL;
list->free(nodeToDel->data);
free(nodeToDel);
list->ListSize--;
return TRUE;
}
else if (list->compare(todel, list->tail->data) == 0) // If the node to be deleted is the tail
{
nodeToDel = list->tail;
list->tail = list->tail->prev;
list->tail->next = NULL;
list->free(nodeToDel->data);
free(nodeToDel);
list->ListSize--;
return TRUE;
}
else
{
nodeToDel = list->head;
while (nodeToDel->next) // Any node other than the head or the tail
{
if (list->compare(todel, nodeToDel->data) == 0) // If the character exists in the list
{
nodeToDel->next->prev = nodeToDel->prev;
nodeToDel->prev->next = nodeToDel->next;
list->free(nodeToDel->data);
free(nodeToDel);
list->ListSize--;
return TRUE;
}
nodeToDel = nodeToDel->next; // Moving to the next node
}
}
return FALSE; // If the character wasn't found in the list return false
}
void printAll(PList list) // Funciton for printing all items in a set
{
PSet temp;
if (list->head == NULL) // If the list is empty
printf("\nThe list is empty.");
else
{
printf("\nThe list is:\n");
temp = list->head;
while (temp) // While there are still nodes left
{
list->print(temp->data); // Call specific function for printing
temp = temp->next; // Move to the next node
}
printf("\n");
}
}
void deleteSet(PList list) // Function for deleting a set
{
PSet temp;
if (!(list->head)) // If the list is empty
printf("\nThe set is empty.\n");
else
{
while (list->head)
{
temp = (list->head);
list->head = list->head->next; // Moving to the next node
if (list->head != NULL)
list->head->prev = NULL;
list->free((temp->data)); // Call specific function for freeing memory
free(temp);
}
list->ListSize = 0;
list->head = NULL;
list->tail = NULL;
printf("\nThe set has been deleted.\n");
}
}
Main:
#include "Header.h"
void prnt_string(void* str) // specific function for printing strings
{
printf("%s ", (char*)str);
}
void free_string(void* str) // specific function for freeing memory
{
free((char*)str);
}
int cmp_str(void* s1, void* s2) // specific function for comparing two strings
{
if (strcmp((char*)s1, (char*)s2) == 0)
return 0;
else if (strcmp((char*)s1, (char*)s2) == 1)
return 1;
else return -1;
}
void prnt_int(void* a) // Specific function for printing integers
{
printf("%d ", (int*)a);
}
void free_int(void* a) // Specific function for freeing integers
{
free(a);
}
int int_comp(void* a, void* b) // Specific function for comparing integers
{
if ((int*)a == (int*)b)
return 0;
else if ((int*)a > (int*)b)
return 1;
else return -1;
}
int main()
{
char ch, tempstr[31], *str;
int n, option, *num, item;
void *temp;
BOOL status;
PList list;
printf("Choose the type you want to work with:\n");
printf("1. Integers\n");
printf("2. Strings\n");
printf("Enter input: ");
scanf("%d", &n);
switch (n)
{
case 1:
list = createSet(int_comp, prnt_int, free_int);
do
{
printf("\n\nChoose the desired action: ('-1' to exit)\n");
printf("1. Create a Set\n");
printf("2. Add To Set\n");
printf("3. Delete From Set\n");
printf("4. Find an Item in The Set\n");
printf("5. Show The Size of The Set\n");
printf("6. Find The Biggest Value In The Set\n");
printf("7. Find The Smallest Value In The Set\n");
printf("8. Delete The Set\n");
printf("Enter input: ");
scanf("%d", &option);
switch (option)
{
case 1:
list = createSet(int_comp, prnt_int, free_int);
printf("\nThe Set Has Been Initialized.\n\n");
break;
case 2:
num = (int*)malloc(sizeof(int));
if (num == NULL)
{
printf("Memory allocation failed!");
deleteSet(list);
return 1;
}
else
{
printf("\nEnter a number: ");
scanf("%d", &num);
status = addToSet(list, num);
if (status == TRUE)
{
printf("Number successfully added to set.\n\n");
printAll(list);
printf("\n");
}
else
{
printf("Operation failed!\nThe number already exists in the set or memory allocation failed.\n\n");
deleteSet(list);
return 1;
}
}
break;
case 3:
printf("\nEnter number: ");
scanf("%d", &item);
status = deleteFromSet(list, item);
if (status == TRUE)
{
printf("Number successfully deleted.\n\n");
printAll(list);
}
else
{
printf("Operation failed!\nThe number does not exist in the set.\n\n");
printAll(list);
printf("\n");
}
break;
case 4:
printf("\nEnter number: ");
scanf("%d", &item);
if (findInSet(list, item) == TRUE)
printf("Item exists in the set.\n\n");
else printf("Item does not exist in the set or the set is empty.\n\n");
break;
case 5:
printf("\nThe size of the set is %d.\n\n", setSize(list));
break;
case 6:
temp = findMax(list);
if (temp == NULL) printf("\nThe set is empty.\n\n");
else printf("\nThe biggest value in the set is %d.\n\n", (int*)temp);
break;
case 7:
temp = findMin(list);
if (temp == NULL) printf("\nThe set is empty.\n\n");
else printf("\nThe smallest value in the set is %d.\n\n", (int*)temp);
break;
case 8:
deleteSet(list);
break;
case -1:
printf("\nExiting Program\n\n");
break;
default:
printf("\nWrong input!\n\n");
break;
}
} while (option != -1);
deleteSet(list);
free(list);
break;
case 2:
list = createSet(cmp_str, prnt_string, free_string);
do
{
printf("\n\nChoose the desired action: ('-1' to exit)\n");
printf("1. Create a Set\n");
printf("2. Add To Set\n");
printf("3. Delete From Set\n");
printf("4. Find an Item in The Set\n");
printf("5. Show The Size of The Set\n");
printf("6. Find The Biggest Value In The Set\n");
printf("7. Find The Smallest Value In The Set\n");
printf("8. Delete The Set\n");
printf("Enter input: ");
scanf("%d", &option);
switch (option)
{
case 1:
list = createSet(cmp_str, prnt_string, free_string);
printf("\nThe Set Has Been Initialized.\n\n");
break;
case 2:
printf("\nEnter a string(max of 30 characters):\n");
scanf("%s", tempstr);
str = (char*)malloc(strlen(tempstr) + 1 * sizeof(char));
if (str == NULL)
{
printf("Memory allocation failed!\n\n");
deleteSet(list);
return 1;
}
strcpy(str, tempstr);
status = addToSet(list, str);
if (status == TRUE)
{
printf("String successfully added to set.\n\n");
printAll(list);
}
else
{
printf("Operation failed!\nThe string already exists in the set or memory allocation failed.\n\n");
deleteSet(list);
return 1;
}
break;
case 3:
printf("\nEnter string(max of 30 characters): ");
scanf("%s", tempstr);
status = deleteFromSet(list, tempstr);
if (status == TRUE)
{
printf("String successfully deleted.\n\n");
printAll(list);
}
else
{
printf("Operation failed!\nThe string does not exist in the set.");
printAll(list);
printf("\n");
}
break;
case 4:
printf("\nEnter string: ");
scanf("%s", tempstr);
if (findInSet(list, tempstr) == TRUE)
printf("Item exists in the set.\n\n");
else printf("Item does not exist in the set.\n\n");
break;
case 5:
printf("\nThe size of the set is %d.\n\n", setSize(list));
break;
case 6:
temp = findMax(list);
if (temp == NULL) printf("\nThe set is empty.\n\n");
else
{
printf("\nThe biggest value in the set is ");
puts((char*)temp);
printf("\n");
}
break;
case 7:
temp = findMin(list);
if (temp == NULL) printf("\nThe set is empty.\n\n");
else
{
printf("\nThe smallest value in the set is ");
puts((char*)temp);
printf("\n");
}
break;
case 8:
deleteSet(list);
break;
case -1:
printf("\nExiting Program\n\n");
break;
default:
printf("\nWrong input!\n\n");
break;
}
} while (option != -1);
deleteSet(list);
free(list);
break;
default:
printf("\nWrong input!\n\n");
break;
}
getch();
return 0;
}
This is the function causing the problem:
void free_int(void* a) // Specific function for freeing integers
{
free(a);
}
The code works perfectly with strings but not with ints.
If someone can point out the problem I'd be really grateful.
Thanks in advance.
Your program may crash because you are overwriting pointer value:
int* num; // [1]
num = (int*)malloc(sizeof(int)); // [2]
scanf("%d", &num); // [3] you are changing value of pointer !!
// scanf ("%d", num); // [4] USE THIS LINE
status = addToSet(list, num);
[1] declaration pointer to int
[2] memory was allocated, it is pointed by num
[3] you are passing pointer to pointer as argument to scanf function, then you are modifing value of pointer (you are not writing some integer value into memory area pointed by num!). So when free function is called it tries to release invalid pointer. It is UB.
[4] scanf("%d",num); use this line to avoid problem with invalid pointer value
The problem was solved. A guy gave it in comments. The problem was that I was using %d to read in a short int. I should have used %hd or I should have used an `int'.
I tried to create a program of singly-linked list using only local variables. I was able to make a working program by using global variables.
The program with local variables compiles but it crashes when I try to traverse the linked list.
I have absolutely no idea what is wrong with the implementation with local variables. What is the problem present in the Implementation with local variables?
ABOUT THE STRUCTURE OF THE PROGRAMS:
I understand that the programs are big so I'll put in something about structure of the program.
The program is structured as a menu driven program. So the initial calls to functions are in main() function
There are 3 options in main() menu - exit, traverse and insertion
Exit returns 0 to exit program while other 2 do function calls
Insertion function itself is arranged as menu-driven program.
It has 3 options - return , insert_begin and insert_end. The last 2 are function calls.
I know there are memory leaks as I haven't freed any memory but I will take care of that after I can understand the problem in the current program.
//WORKING IMPLEMENTATION USING GLOBAL VARIABLE
#include<stdio.h>
#include<stdlib.h>
#define MIN 0
#define MAX 2
#define INS_MIN 0
#define INS_MAX 2
typedef struct node
{
int data;
struct node *next;
}sll_node;
sll_node *start = NULL;
void intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Exit");
printf("\n\t01 Traverse the list");
printf("\n\t02 Insertion into the list");
}
void insert_begin()
{
sll_node *node = malloc(sizeof(sll_node));
if(node == NULL)
{
printf("\n\tNot enough menory");
exit(-1);
}
int data;
printf("\n\tData to be entered: ");
scanf("%d", &data);
node->data = data;
node-> next = start;
start = node;
}
void insert_end()
{
sll_node *node = malloc(sizeof(sll_node));
if(node == NULL)
{
printf("\n\tNot enough menory");
exit(-2);
}
if(start == NULL)
insert_begin();
else
{
printf("\n\tData to be entered: ");
scanf("%d", &(node->data));
node-> next = NULL;
sll_node *node2;
for(node2 = start; node2->next != NULL; node2 = node2->next)
;
node2->next = node;
}
}
void insert_intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Insertion Done");
printf("\n\t01 Insert at beginning");
printf("\n\t02 Insert at end");
}
void insertion()
{
short choice;
while(1)
{
choice = -1;
while(choice < INS_MIN || choice > INS_MAX)
{
insert_intro();
printf("\n\n\tEnter your chocie: ");
scanf("%d", &choice);
}
switch(choice)
{
case 0:
return;
case 1:
insert_begin();
break;
case 2:
insert_end();
break;
}
}
}
void traverse()
{
if(start == NULL)
printf("\n\n\tLinked list is empty");
else
{
printf("\n\n\t");
for(sll_node *node = start; node != NULL; node = node->next)
printf("%d ", node->data);
}
getch();
}
int main()
{
short choice;
while(1)
{
choice = -1;
while(choice < MIN || choice > MAX)
{
intro();
printf("\n\n\tEnter your choice: ");
scanf("%d", &choice);
}
switch(choice)
{
case 0:
return 0;
case 1:
traverse();
break;
case 2:
insertion();
break;
}
}
return 0;
}
//COMPILES BUT CRASHES - Same program but with local variable start and variable passing between functions
#include<stdio.h>
#include<stdlib.h>
#define MIN 0
#define MAX 2
#define INS_MIN 0
#define INS_MAX 2
typedef struct node
{
int data;
struct node *next;
}sll_node;
void intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Exit");
printf("\n\t01 Traverse the list");
printf("\n\t02 Insertion into the list");
}
sll_node* insert_begin(sll_node *start)
{
sll_node *node = malloc(sizeof(sll_node));
if(node == NULL)
{
printf("\n\tNot enough menory");
exit(-1);
}
int data;
printf("\n\tData to be entered: ");
scanf("%d", &data);
node->data = data;
node-> next = start;
return node;
}
sll_node* insert_end(sll_node *start)
{
sll_node *node = malloc(sizeof(sll_node));
if(node == NULL)
{
printf("\n\tNot enough menory");
exit(-2);
}
if(start == NULL)
start = insert_begin(start);
else
{
printf("\n\tData to be entered: ");
scanf("%d", &(node->data));
node-> next = NULL;
sll_node *node2;
for(node2 = start; node2->next != NULL; node2 = node2->next)
;
node2->next = node;
}
return start;
}
void insert_intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Insertion Done");
printf("\n\t01 Insert at beginning");
printf("\n\t02 Insert at end");
}
sll_node* insertion(sll_node *start)
{
short choice;
while(1)
{
choice = -1;
while(choice < INS_MIN || choice > INS_MAX)
{
insert_intro();
printf("\n\n\tEnter your chocie: ");
scanf("%d", &choice);
}
switch(choice)
{
case 0:
return start;
case 1:
start = insert_begin(start);
break;
case 2:
start = insert_end(start);
break;
}
}
}
void traverse(sll_node *start)
{
if(start == NULL)
printf("\n\n\tLinked list is empty");
else
{
printf("\n\n\t");
for(sll_node *node = start; node != NULL; node = node->next)
printf("%d ", node->data);
}
getch();
}
int main()
{
sll_node *start = NULL;
short choice;
while(1)
{
choice = -1;
while(choice < MIN || choice > MAX)
{
intro();
printf("\n\n\tEnter your choice: ");
scanf("%d", &choice);
}
switch(choice)
{
case 0:
return 0;
case 1:
traverse(start);
break;
case 2:
start = insertion(start);
break;
}
}
return 0;
}
You are not returning anything from insertion() function when item is added to a list. So linked list may not get constructed properly.
Probably, you should return start only when its added at the beginning, otherwise start in main() will not point to head of the list.
sll_node* insertion(sll_node *start)
{
...
switch(choice)
{
case 0:
return start;
case 1:
start = insert_begin(start);
return start; //<----- return node
break;
case 2:
start = insert_end(start);
break;
}
...
}
Change short choice to int choice.
Why does this make a difference?
Short answer is that printf("%d") expects an integer.
The long answer is "%d" describes the data type you are passing to printf as an integer (which is commonly 4 to 8 bytes), and you're giving it a datatype of short - which is commonly 2 bytes long. When your program reads the input and stores it at the pointer, &choice, it writes 4 bytes starting at that address (but only 2 were reserved). This causes a segmentation fault and will crash your program.
Here's a list to some printf documentation. You'll notice that to pass a short to printf you would write %hd instead of %d
When i compile your code on my computer, it works, but i changed "short choice" to "int choice", because scanf("%d", &choice) takes 4 bytes to write on, and when choice is short it crashes, because short has only 2 bytes, therefore stack corruption will occur, my be on your computer this corruption damage the "start" pointer.
About the crash. Change the argument start in both functions insert_begin and insert_end to sll_node ** start, and when assigning new value, use the expression *start = your-new-value. It is because you have to pass a pointer to the local variable start which is also pointer. You do not need to change function traverse.
About memory leaks, let me to point-out that when you call insert_begin from inside insert_end, the node created from insert_end is left unused. before exit() and the return in main() you should free the list.
Yes, sorry. There was another bug hard to see. It was at 2 lines where you read (choice).
short choice;
...
// It is ERROR to use "%d" with (short choice), because the stack will
// be overwritten with unsuspected results. The format specifier "%hd"
// say to compiler that (&choice) point to a short 16-bit integer,
// not 32-bit
scanf("%hd", &choice);
This is slightly different version, tested, without memory leaks.
//
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#define MIN 0
#define MAX 2
#define INS_MIN 0
#define INS_MAX 2
typedef struct node
{
int data;
struct node *next;
} sll_node;
void clear_list(sll_node** start)
{
assert(start != NULL);
sll_node* node = *start;
while (node != NULL)
{
sll_node* element = node;
node = element->next;
free(element);
}
*start = NULL;
}
void intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Exit");
printf("\n\t01 Traverse the list");
printf("\n\t02 Insertion into the list");
}
void insert_begin(sll_node** pstart)
{
sll_node* node = (sll_node*)malloc(sizeof(sll_node));
if (node == NULL)
{
printf("\n\tNot enough menory");
clear_list(pstart);
exit(-1);
}
int data;
printf("\n\tData to be entered: ");
scanf_s("%d", &data);//scanf
node->data = data;
node->next = *pstart;
// update the local variable start passed from main to point just inserted node
*pstart = node;
}
void insert_end(sll_node** start)
{
assert(start != NULL);
if (*start == NULL)
{
insert_begin(start);
}
else
{
sll_node* node = (sll_node*)malloc(sizeof(sll_node));
if (node == NULL)
{
printf("\n\tNot enough menory");
clear_list(start);
exit(-2);
}
printf("\n\tData to be entered: ");
scanf("%d", &(node->data));
node->next = NULL;
sll_node* node2;
for(node2 = *start; node2->next != NULL; node2 = node2->next)
;
node2->next = node;
}
}
void insert_intro()
{
system("cls");
printf("\n\tThese are the various options:\n");
printf("\n\t00 Insertion Done");
printf("\n\t01 Insert at beginning");
printf("\n\t02 Insert at end");
}
void insertion(sll_node** start)
{
short choice;
while(1)
{
choice = -1;
while(choice < INS_MIN || choice > INS_MAX)
{
insert_intro();
printf("\n\n\tEnter your chocie: ");
scanf("%hd", &choice);
}
switch(choice)
{
case 0:
return;
case 1:
insert_begin(start);
break;
case 2:
insert_end(start);
break;
}
}
}
void traverse(sll_node *start)
{
if (start == NULL)
printf("\n\n\tLinked list is empty");
else
{
printf("\n\n\t");
for(sll_node *node = start; node != NULL; node = node->next)
printf("%d ", node->data);
}
getch();
}
int main()
{
sll_node *start = NULL;
short choice;
while(1)
{
choice = -1;
while(choice < MIN || choice > MAX)
{
intro();
printf("\n\n\tEnter your choice: ");
scanf("%hd", &choice);
}
switch(choice)
{
case 0:
clear_list(&start);
return 0;
case 1:
traverse(start);
break;
case 2:
insertion(&start);
break;
}
}
return 0;
}
P.S. Very hard to edit! I'm new here and do not have enough experience. Wasted a lot of time to edit!