How to fix infinite loop with struct in C - c

I have a problem with the struct when storing data. I want to make a sentinel loop so please have a look and help me thank you.
#include<stdio.h>
#include<stdlib.h>
struct Vehichle
{
char vecType[100];
char plateNo[10];
float hours;
};
struct Parking
{
int parkNo ;
// 1 =true 0=false
int availability;
};
int main()
{
int c = 0;
int x;
struct Vehichle vehicle[c];
struct Parking park[50];
int counter = 1;
while(x!=-1)
{
printf("Enter -1 to end: \n");
scanf("%d", &x);
printf("Enter Vehicle Type etc: suv,mpv and more:");
scanf("%d",&vehicle[x].vecType);
printf("Please enter parking Number :");
scanf("%d",&park[x].parkNo);
park[x].availability = 1;
counter++;
}
}
I expect that after it is stored in the struct, the program will loop.

There are a number of problems in your code. Here is your code where I have added some comments:
int main()
{
int c = 0;
int x; // UPS: x is uninitialized
struct Vehichle vehicle[c]; // UPS: c is zero so you don't get an array
struct Parking park[50];
int counter = 1;
while(x!=-1) // UPS: Use of uninitialized x
{
printf("Enter -1 to end: \n");
scanf("%d", &x);
printf("Enter Vehicle Type etc: suv,mpv and more:");
scanf("%d",&vehicle[x].vecType); // UPS: vecType is char array so
// use %s instead of %d
// and don't use a &
printf("Please enter parking Number :");
scanf("%d",&park[x].parkNo);
park[x].availability = 1;
counter++;
}
}
Besides that you have a problem when the user input is -1. The current code just continues and adds an element at index -1. That's illegal.
To fix add an extra line after the scanf. Like:
scanf("%d", &x);
if (x == -1) break; // Stop the while loop
With that change you can do while(1) instead of while(x!=-1)
Some extra comments:
You should check that the user input (aka x) is within the valid range to be used as array index.
You should also check the return value of scanf. Like:
if (scanf("%d", &x) != 1)
{
// Invalid input"
... error handling ...
}

(1) Below is an updated code as your code had several problems.
I'm sure that looking at the below code, you would be able to understand the mistakes in your code.
Feel free to use this as the base for writing your own version.
(2) Please read the inline comments carefully. The comments elaborately
explain the intention of that section of code
(3) This is just a quick code. I've not compiled/run/tested this code.
My intention is just to give you an idea about it with one possible example.
/* A very basic parking manager module
When a vehicle comes in for parking
a)capture vehicle info & parking lot number where it is parking
b)mark that lot as unavailable
When the vehicle is leaving the parking,
capture parking lot number which is being emptied,
and mark that lot as available
And, have some fun on the way.
*/
#include<stdio.h>
#define YOU_ARE_TRAPPED_BY_THE_BIG_BAD_GREEN_SCARY_MONSTER ({printf("HA HA HA, You didn't read and follow the inline comments !!\nNow stand up, jump 3 times, then sit down, and read all the comments again and do the min code modif to make me go away, else i won't let you escape the parking lot ... hoo ha ha ha ha >-)\n"); updateVehicleParkingInfo=1;})
#include<stdlib.h>
struct Vehichle{
char vecType[100]; //type of vehicle eg suv,mpv and more...
char plateNo[10]; //number plate of the vehicle
float hours; //???
};
struct Parking{
int parkNo ; //parking lot num
bool availability; //Is tbis parking space available? Yes/No
};
struct VehicleParkingInfo{
struct Vehicle vehicle; //vehicle info
struct Parking parking; //corresponding parking info
};
//maximum number of parking lots that the parking space has
#define MAX_PARKING_LOTS 10
//parking lot avaialble flags
#define PARKING_LOT_AVAILABLE true
#define PARKING_LOT_UNAVAILABLE false
//flags for vehicle coming in or leaving
#define VEHICLE_ENTERING true
#define VEHICLE_LEAVING false
void main(){
int updateVehicleParkingInfo; //flag indicating that user wants to update parking info.
int vehicleDirection; //flag for indicating whether the vehicle is coming in or going out of the parking
int parkingIdx; //index of the parking lot to fetch values from.
//array for info about all the parking lots
struct VehicleParkingInfo vehicleParkingInfo[MAX_PARKING_LOTS];
//initialize the parking & vehicle info of all the parking lots to zeros
memset(vehicleParkingInfo,0,MAX_PARKING_LOTS*sizeof(VehicleParkingInfo));
//for each parking lot, mark it as available and assign parking lot numbers serially
for(parkingIdx = 0; parkingIdx < MAX_PARKING_LOTS; parkingIdx++){
vehicleParkingInfo[parkingIdx].parking.parkNo = parkingIdx;
vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_AVAILABLE;
}
//get user's input if parking info needs to be updated or it is time to close and go home
printf("Update parking info? Enter 0 to end");
scanf("%d",&updateVehicleParkingInfo);
/*
**** SENTINEL LOOP ****
Continue updating the parking info until the user wants to even for unlimited number of times.
Stop only when user enters a specific value i.e. 0.
*/
while(updateVehicleParkingInfo != 0){
printf("vehicle direction? 1 for entering, 0 for leaving:");
scanf("%d",&vehicleDirection);
if(vehicleDirection == VEHICLE_ENTERING){
do{
printf("Please enter parking Number:");
scanf("%d",&parkingIdx);
//*** CRASH ALERT!!! *** Following code can crash if parkingIdx is < 0, or >= MAX_PARKING_LOTS
//TODO: (1) Add sanity check for parkingIdx (2) Add corrective steps if sanity check fails
//if parking is not available, print an error message
if(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_UNAVAILABLE){
//TODO: change the below messages to fine-tune fun, humor, teasing etc levels (remember humor setting of TARS from Interstellar?)
printf("There is some other vehicle parked in this parking lot, please enter another parking lot number\n");
printf("BTW, I know which lots are available, but I won't tell you ... hehehe >-) \n, keep trying ...hoo hoo hooo\n");
}
//check if the requested parking lot is available, if yes, then take further actions, else request a new parking lot number
}while(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_UNAVAILABLE);
printf("Yipee, this parking lot is available\n");
//mark this parking lot number as being used so that another vehicle cannot come here.
vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_UNAVAILABLE;
//get vehicle type info and
// *** CRASH ALERT!!! *** The scanf below will crash if the user enters more 99+ characters (buffer overflow)
// Best is to use fgets or getline with the stdin as the stream.
// Ref https://stackoverflow.com/questions/4023895/how-do-i-read-a-string-entered-by-the-user-in-c
// TODO: Replace below scanf() with a better/safer implmentation
printf("Enter Vehicle Type etc: suv,mpv and more:");
scanf("%s",vehicleParkingInfo[parkingIdx].vehicle.vecType);
//TODO: other steps.
}
if(vehicleDirection == VEHICLE_LEAVING){
do{
printf("Please enter parking Number:");
scanf("%d",&parkingIdx);
//*** CRASH ALERT!!! *** Following code can crash if parkingIdx is < 0, or >= MAX_PARKING_LOTS
//TODO: (1) Add sanity check for parkingIdx (2) Add corrective steps if sanity check fails
//if parking is available, print an error message
if(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_AVAILABLE){
printf("It appears that the parking lot number is incorrect, please enter correct parking lot number\n");
}
//check if the requested parking lot is available, if yes, then request a new parking lot number, else proceed further
}while(vehicleParkingInfo[parkingIdx].parking.availability == PARKING_LOT_AVAILABLE);
printf("Bye bye, drive safely\n");
//mark this parking lot number as available for other incoming vehicles.
vehicleParkingInfo[parkingIdx].parking.availability = PARKING_LOT_AVAILABLE;
}
//get user's input if parking info needs to be updated or it is time to close and go home
printf("Update parking info? Enter 0 to end");
scanf("%d",&updateVehicleParkingInfo);
//TODO: remove the following line of code before running the program
YOU_ARE_TRAPPED_BY_THE_BIG_BAD_GREEN_SCARY_MONSTER;
//go back to while loop,
//check if the vehicle parking info needs to be updated,
//break if the user has entered 0
}//end of the Sentinel loop
//the above loop will run indefinitely. The user has quite a lot of ways to come out of the loop
//(1) Enter the sentinel value '0', (easiest path)
//(2) Somehow stop the program e.g. by banging his/her head really hard on the computer such that computer breaks .. etc
}//end of main()

Related

In C Scanf not grabbing inputs past the first instance of scanf

Coding in visual studio code
#include<stdio.h>
int main(){
char firstLetterofName;
int numOfVisits;
float priceOfDrink; //Creating the variables leaving them empty for now
float total;
printf("Hello! What is your name?\n");
scanf("%c", &firstLetterofName); //Asking for an inputting the first letter of users name
printf("How many times have you visited Starbucks in a month\n");
scanf("%d", &numOfVisits); //Asking and inputting number of visits
printf("What is the price of the drink you order?\n");
scanf("%f", &priceOfDrink); //Asking and inputting price of drink
total = priceOfDrink * numOfVisits;
printf("Wow %c! You have spent $%d on Starbuck!", firstLetterofName, total);
return 0;
}
First attempt using full name Terminal outputs
PS C:\C Cpp> cd "c:\C Cpp\" ; if ($?) { gcc test.c -o test } ; if ($?) { .\test }
Hello! What is your name?
Logan
How many times have you visited Starbucks in a month
What is the price of the drink you order?
Wow L! You have spent $0 on Starbuck!
Second attempt using only first letter
PS C:\C Cpp> cd "c:\C Cpp\" ; if ($?) { gcc test.c -o test } ; if ($?) { .\test }
Hello! What is your name?
L
How many times have you visited Starbucks in a month
5
What is the price of the drink you order?
2.0
Wow L! You have spent $0 on Starbuck!
PS C:\C Cpp>
Expected output is Wow L! You have spent $10.0 on starbucks
For the name part it is suppose to only take the first letter.
In C Scanf not grabbing inputs past the first instance of scanf
With input "Logan\n", code scans in the 'L' as the firstLetterofName with the "ogan\n" reamaining in stdin for the next input function.
scanf("%c", &firstLetterofName);
With input "ogan\n", scanf() fails and returns 0. numOfVisits was not changed. Code unfortunately did not not check the return value of scanf() to test success.
scanf("%d", &numOfVisits); // FAILED
To quickly discern scanf() troubles, check scanf() return values for success.
Do not rely on the user to enter compliant text. Robust code watches out for too much data, not enough data, non-numeric data, etc. User input is evil.
Consider using fgets() to read a line of user input and then parse the resultant string.
#include<stdio.h>
int main(){
char firstLetterofName;
int numOfVisits;
float priceOfDrink; //Creating the variables leaving them empty for now
float total;
printf("Hello! What is your name?\n");
scanf("%c", &firstLetterofName); //Asking for an inputting the first letter of users name
//clear the input stream
fflush(stdin);
printf("How many times have you visited Starbucks in a month\n");
scanf("%d", &numOfVisits); //Asking and inputting number of visits
printf("What is the price of the drink you order?\n");
scanf("%f", &priceOfDrink); //Asking and inputting price of drink
total = priceOfDrink * numOfVisits;
printf("Wow %c! You have spent $%f on Starbuck!", firstLetterofName, total);
return 0;
}
Use fflush(stdin) to flush the input stream. Availabe in gcc

How to use isdigit() for a pin while loop [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This program accepts any four digit number as the pin , so i used a strlen() to find out whether the pin is has four characters, but I need to make sure that user enters four numbers, how do I use isdigit() before the loop and for the loop condition?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char pin [4];
printf("Please enter your pin : \n") ;
scanf("%4s" , &pin) ;
system("cls") ;
while (strlen(pin) != 4) {
count = count + 1 ;
if(count < 3){
printf("Invalid Pin \n") ;
printf("Please enter your pin again \n") ;
scanf("%4s", &pin) ;
system("cls");
}
else if (count == 3){
printf("Sorry you can't continue , Please contact your bank for assistance !") ;
return 0 ;
}
}
There are so many issues with this code I may not have covered every one of them in this answer:
Where is your main function? You can't have code outside a function; that doesn't work. C code other than global variable declarations, assignments to constant values, typedefs, struct and enum definitions, must go in a function. In your case you probably want the main function to house the code starting at line 6.
When calling scanf with a string argument, don't take the address of the string - the array is a reference in and of itself.
Calling strlen(pin) before any value has been copied into pin is 100% undefined behavior. Since the memory is uninitialized the strlen function will keep looking for a null character and possibly go out of the array bounds.
C strings are null-terminated. When you declare a string intended to hold n characters, you need to declare the array with a size of n+1 to have room for the null character.
First to answer your question
I would write a helper function 'validatePin' which would check the pin length and validate that the pin is a numeric pin, you can extend this function to do any other validation you require. It might look something like the following
const int PIN_OK = 0;
const int PIN_INVALID_LEN = -1;
const int PIN_INVALID_CHARS = -2;
int validatePin(const char *pin)
{
// Valdiate PIN length
if (strlen(pin) != 4) return PIN_INVALID_LEN;
// Validate PIN is numeric
for (int i = 0; i < 4; ++i)
{
if (!isdigit(pin[i])) return PIN_INVALID_CHARS;
}
return PIN_OK;
}
Then you can adjust your while loop to look something like the following
while (validatePin(pin) != PIN_OK)
{
....
}
Other points regarding your code.
Your char buffer used for scanf does not account for the null terminator. You need to increase the buffer size.
The char array is already giving you the address of the buffer, there is no need to use & to take the address of the char array in scanf.
I have not run your code, so there might be other issues that I missed at first glance.
There are a number of ways to go about doing what you need to do. You can either check your input length, or just validate what it is you have read, your choice. One approach would be:
#include <stdio.h>
#include <ctype.h>
enum { TRIES = 3, NPIN };
int main (void) {
char pin[NPIN+1] = "";
size_t tries = 0, pinok = 0;
for (; tries < TRIES; tries++) { /* 3 tries */
printf ("Please enter your pin : ");
if (scanf (" %4[^\n]%*c", pin) == 1) { /* read pin */
pinok = 1;
size_t i;
for (i = 0; i < NPIN; i++) /* validate all digits */
if (!isdigit (pin[i]))
pinok = 0;
if (pinok) /* if pin good, break */
break;
}
}
if (!pinok) { /* if here and not OK, call bank */
fprintf (stderr, "Sorry you can't continue, Please contact "
"your bank for assistance.\n") ;
return 1;
}
printf ("\n correct pin : %s\n\n", pin); /* your pin */
return 0;
}
(note: to protect against an excessively long string entered at one time, you should empty stdin at the end of the outer for loop each iteration)
Example Use/Output
Failed case:
$ ./bin/pin
Please enter your pin : a555
Please enter your pin : 555a
Please enter your pin : 55a5
Sorry you can't continue , Please contact your bank for assistance.
Successful case:
$ ./bin/pin
Please enter your pin : 2345
correct pin : 2345
Look it over an let me know if you have any questions.

Galton Box/Bean Machine-C

I want to code a simple bean machine program. The program will accept user input for the number of balls and the number of slots, and will calculate the path of each ball. The number of balls in each slot will be printed as a histogram as well.
I tried my best to keep the code short and sweet, yet the best I have managed is 112 lines long. When I ran my code, I received no errors. However, the output seems to have run into some sort of an infinity loop (The '#' symbol which was used to represent numbers in the histogram keeps on printing forever for some reason unknown to me).
Apparently, there is something wrong with my logic somewhere... or a silly little mistake in syntax(but it would have shown up as error, wouldn't it?)... In a nutshell, I cannot figure out exactly what is the problem. (I attempted to walk through the whole code process from start to finish, but my mind kept getting tangled up somewhere in the middle of the code, nowhere near the end of the code either).
Where exactly does my logic go wrong?(Or have I taken the wrong approach to the whole problem?) I do not wish to know the correct code, so that I am able to learn during the whole process of re-editing my code.
Any help (hopefully no model-code answers though), even as a single comment, is tremendously appreciated! :)
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <stdbool.h>
#include <time.h>
//Pls excuse my extensive use of libraries even though I don't really use them
int intchecker(float x)
{
if (floor(x)==x && ceilf(x)==x)
{
return 0;
}
else {
return 1;
}
}
int main(){
char line[] = " +----+----+----+----+----+----+----+----+----+----+---+";
char numbers[] = " 0 5 10 15 20 25 30 35 40 45 50";
float balls,slots;
int slotarry[9],tlevel,ballnum,column,lcounter=0,slotsduplicate=1,y;//tlevel-number of levels in the triangle
srand(time(NULL));
int r;
printf("==========================================================\nGalton Box Simulation Machine\n==========================================================\n");
printf("Enter the number of balls [5-100]: ");
scanf("%f",&balls);
while (balls>100 || balls<5) {
printf("\nInput is not within the range. Please try again.");
printf("\nEnter the number of balls [5-100]: ");
scanf("%f",&balls);
}
while (intchecker(balls)==1) {
printf("\nInput is not an integer. Please try again.");
printf("\nEnter the number of balls [5-100]: ");
scanf("%f",&balls);
}
printf("Enter the number of slots [2-10] : ");
scanf("%f",&slots);
while (slots>10 || slots<2) {
printf("\nInput is not within the range. Please try again.");
printf("\nEnter the number of slots [2-10] : ");
scanf("%f",&slots);
}
while (intchecker(slots)==1) {
printf("\nHow can there be a fraction of a slot? Please re-enter slot number.");
printf("\nEnter the number of slots [2-10] : ");
scanf("%f",&slots);
}
tlevel=slots-1;
for(ballnum=1,column=0;balls>0;balls--,ballnum++,column++){
if (column%5==0){
printf("\n");
}
if (ballnum<10){
printf("[0%d]",ballnum);
}
else{
printf("[%d]",ballnum);
}
for(;tlevel>0;tlevel--){
r = rand() % 2;
if (r==0){
printf("R");
}
else {
printf("L");
lcounter++;
}
}
slotarry[lcounter]++;
tlevel=slots-1;
lcounter=0;
printf(" ");
}
printf("\n\n%s",numbers);
printf("%s",line);
char line2[] = "\n +----+----+----+----+----+----+----+----+----+----+---+";
for(;slotsduplicate<=slots;slotsduplicate++){
if (slotsduplicate<10){
printf("0%d|",slotsduplicate);
}
else{
printf("%d|",slotsduplicate);
}
y=slotarry[slotsduplicate];
if (y==0){
printf(" 0");
}
else{
for (;y>0;y--){
printf("#");
}
printf(" %d",slotarry[slotsduplicate]);
}
printf("%s",line2);
}
return 0;
}
Note:This is not completely error-free. This is just my first draft. I just wish to find out why there is an infinite loop.
Here's how I found the problem. First of all, I think it is a bit of a code smell to have a for loop without anything in the initial assignment section. Couple that with the fact that it seems to print # forever, and it looks like y has a garbage value at the beginning of the loop to print the #s.
So I ran your code in the debugger and paused it when it started printing loads of hashes. I checked the value of y and sure enough it was some unfeasibly high number.
Then I checked where y comes from and found you get it from slotarray. I printed it in the debugger and found that all the values in it were unfeasibly high or massively negative numbers. Obviously, slotarray wasn't being initialised correctly, so I looked for where it was initialised and bingo!
Stack variables (of which slotarray is one) must be explicitly initialised in C. I fixed your code with a call to memset.
The whole debugging process I have just outlined took something less than a minute.
ETA As #EOF points out, there is another bug in that slotarray is defined to contain nine slots (indexed 0 - 8) but you allow people to enter 10 slots. This is a buffer overflow bug.

Get program to return an error message and return to start of program if value entered is outside range

I'm a complete beginner with C and am currently trying to write a program where the user can enter results from football league games and calculate the teams' scores after each game.
There are 6 teams in the league and the user is required to choose a team at the start of the program in order to input a score for that team. What I would like to do is have the program return an error message if the user enters a value that is not between 1 and 6.
I've tried two different approaches but I'm not sure if either are in the right direction. One approach is shown below for the home team.
#include <stdio.h>
int main(void)
{
int h=0; /*Home team number*/
int a=0; /*Away team number*/
int hgoals=0; /*Goals scored by home team*/
int agoals=0; /*Goals scored by away team*/
/*User inputs home team number*/
printf("Home team number: ");
scanf_s("%d",&h);
/*Returns error message if home team number is not between 1 & 6*/
if(1<!h<!6){
printf("Please enter a number between 1 & 6\n");
}
return 0;
}
The other idea I had was to use an if statement where if the number entered is between 1 & 6 then nothing would happen, and use else to print the error message if the number is not between 1 & 6, but I'm not sure how to make an if statement that does nothing. I'm also thinking that I would have to put the entire program inside a loop to get it to restart if the number is not between 1 & 6.
Any help is appreciated!
Change the condition in the if statement :
if(h < 1 || h > 6)
printf("Please enter a number between 1 and 6\n");

Return not ending method in c

edit - i figured out the arithmetic error but I still have the return error
For some reason my program is giving me two errors. First error is that the "return" at the end of each of my methods() are not ending the method and bring me back to main. My second question is at line 23 where pfNum = mainSize/pageSize; is giving me a "SIGFPE, arithmetic exception" not sure why both of these are occuring can anyone help me out?
Thanks
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* Define page table as dynamic structure containing virtual page and page frame
and initialize variable as pointer to structure */
struct table{
int vp;
int pf;
}*pageTable = NULL;
/* Declare global var's */
int mainSize,pageSize,policy,pfNum;
/**********************************************************************/
void option1(){
/* Declare local var's */
int k;
/* Prompt for main memory size, page size, and replacement policy */
printf("Enter main memory size(words): ");
scanf("%d",&mainSize);
printf("Enter page size(words/page): ");
scanf("%d",&pageSize);
printf("Enter replacement policy(0=LRU, 1=FIFO): ");
scanf("%d",&policy);
pfNum = mainSize/pageSize;
/* Allocate and initialize page table based on number of entries */
pageTable = malloc(pfNum *sizeof(pageTable));
for(k=0;k<pfNum;k++){
pageTable[k].vp=-1;
pageTable[k].pf=k;
}
return;
}
/**********************************************************************/
void option2(){
/* Declare local var's */
int va,page,offset,i=0,temp;
/* Prompt for virtual address */
printf("Enter virtual memory address to access: ");
scanf("%d",&va);
/* Translate virtual mem addr to virtual page and offset*/
page = va/pageSize;
offset = va%pageSize;
/* Check for end of table, unallocated entry, or matched entry in table
and update table appropriately; while none of three cases, keep looping */
while(i<pfNum && pageTable[i].vp!=1 && pageTable[i].vp!=page)
i++;
if(i<=pfNum){
int j;
temp = pageTable[0].pf;
for(j=1;j<pfNum;j++)
pageTable[j-1]=pageTable[j];
pageTable[j].vp=page;
pageTable[j].pf=temp;
printf("Page Fault!");
}
else if(pageTable[i].vp==-1){
pageTable[i].vp = page;
printf("Page fault!");
}
else if(pageTable[i].vp==page){
temp = pageTable[i].pf;
int l,address;
for(l=i+1;l<pfNum-1;l++)
pageTable[l-1]=pageTable[l];
pageTable[l].vp = page;
pageTable[l].pf = temp;
address = (temp*pageSize)+offset;
printf("Virtual address %d maps to physical address %d",va,address);
}
return;
}
/**********************************************************************/
void option3(){
/* Declare local var's */
int u;
for(u=0;u<pfNum;u++ && pageTable[u].vp!=-1)
printf("VP %d --> PF %d",pageTable[u].vp,pageTable[u].pf);
/* Print out each valid virtual page and page frame pair in table */
return;
}
/**********************************************************************/
int main(){
/* Declare local var's */
int choice;
/* Until user quits, print menu of options, prompt for user input, and select appropriate option */
printf("/n");
printf("Virtual memory to Main memory mapping:\n");
printf("--------------------------------------\n");
printf("1) Set parameters\n");
printf("2) Map virtual address\n");
printf("3) Print page table\n");
printf("4) Quit\n");
printf("\n");
printf("Enter Selection: ");
scanf("%d",&choice);
printf("\n");
while(choice!=4){
if(choice==1)
option1();
else if(choice==2){
option2();
}
else if(choice==3)
option3();
}
printf("Goodbye. Have a nice day.");
return 1;
}
The "SIGFPE, arithmetic exception" exception is most likely caused by division by zero.
One problem is that once you've made your initial choice, nothing changes choice again, so the program goes around the loop, executing your initial choice (possibly doing nothing at all, since you don't validate for zero, negative choices, or values greater than four). This might give the appearance that your functions "don't return" but actually they do return; they just get called again almost immediately.
You probably need to prompt for a new choice each time around the loop, which suggests a function to prompt and return the choice which you call from a while loop.
You have at least one "/n" where you probably intended "\n". Your farewell message is missing its newline; so are a number of other messages (such as the "Page Fault!" messages). You don't check that your input functions were successful. You don't check that the memory allocation was successful.
Your SIGFPE probably comes from division by zero; print the values you're processing before you execute the division.

Resources