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.
Related
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()
I'm super new to C programming, only taking it for a required course in uni and finally getting done with my final project this week.
Problem is every time I run this code I get an error message that says "segmentation fault: 11" and I'm not sure what that means.
The code is supposed to run two-player race. Each player has a pre-determined "speed modifier", aka a number from 0-9. A random number from 1-10 is generated; if the speed modifier + the random number doesn't exceed 10, then the speed modifier is added and the car moves that total amount of "spaces". The whole race track is 90 "spaces".
Every time I run this code it works somewhat fine (more on that later) for one or two iterations, then gives out that error message. I normally don't ask for homework help online but I'm honestly so confused. Any help at all would be super appreciated.
Here is the relevant code:
Race (main) function:
int race(struct car cars[4], int mode)
{
/* Define variables. */
int endgame, i, x, y, first=-1, second=-1, randnum, spaces[]={};
char input[100];
/* Declare pointer. */
int *spacesptr=spaces;
for (i=0; i<mode; i++)
{
/* Array spaces will keep track of how many spaces a car has moved. Start each car at 0. */
spaces[i]=0;
}
/* Clear screen before race. */
system("cls");
/* Print message to indicate race has started. */
printf("\n3...\n2...\n1...\nGO!\n\n");
/* Open do while loop to keep race running until it is over. */
do
{
/* Conditions for two player mode. */
if (mode==2)
{
/* Run the next block of code once for each player. */
for (i=0; i<mode; i++)
{
/* Generate random integer from 1-10 to determine how many spaces the car moves. */
x=10, y=1;
randnum=(getrandom(x, y));
spaces[i]=spaces[i]+randnum;
/* Call function speedmod to determine if speedmodifier should be added. */
speedmod(cars, spaces, randnum);
/* Rank players. */
if (spaces[i]>89)
{
if (first==-1)
{
first=i;
}
else if (second==-1)
{
second=i;
}
}
}
}
...
/* Call function displayrace to display the race. */
displayrace(cars, spaces, mode);
/* Call function endgame to determine if the race is still going. */
endgame=fendgame(mode, spaces);
if (endgame==0)
{
/* Ask for player input. */
printf("Enter any key to continue the race:\n");
scanf("%s", input);
/* Clear screen before loop restarts. */
system("cls");
}
} while (endgame==0);
}
Random number function:
int getrandom(int x, int y)
{
/* Define variable. */
int randnum;
/* Use time seed. */
srand(time(0));
/* Generate random numbers. */
randnum=(rand()+y) % (x+1);
return randnum;
}
Add speed modifier function:
void speedmod(struct car cars[4], int spaces [], int go)
{
/* Declare pointer. */
int *spacesptr=spaces;
/* If the number of spaces plus the speed modifier is less than or equal to ten... */
if (spaces[go]+cars[go].speedmod<=10)
{
/* ...add the speed modifier to the number of spaces moved. */
spaces[go]=spaces[go]+cars[go].speedmod;
}
}
Display race function:
void displayrace(struct car cars[4], int spaces[], int mode)
{
/* Define variables. */
int i, j;
/* Declare pointers. */
int *spacesptr=spaces;
struct car *carsptr=cars;
/* Open for loop. */
for (i=0; i<mode; i++)
{
/* Print racecar number. */
printf("#%d\t", cars[i].carnumber);
/* For every space the car has moved... */
for (j=0; j<spaces[i]; j++)
{
if (j<=90)
{
/* ...print one asterisk. */
printf("*");
}
}
/* New line. */
printf("\n");
}
}
End game function:
int fendgame(int mode, int spaces[])
{
/* Define variables. */
int racers=0, endgame=0, i;
/* Declare pointer. */
int *spacesptr=spaces;
/* Open for loop. */
for (i=0; i<mode; i++)
{
/* If any of the racers have not yet crossed the finish line (90 spaces)... */
if (spaces[i]<=90)
{
/* ...then add to the number of racers still in the game. */
racers++;
}
}
/* If all the racers have crossed the finish line... */
if (racers==0)
{
/* ...then end the game. */
endgame=1;
}
return endgame;
}
Now to be more specific on the issue...it's messing up somewhere on the "for" loop in the race function. For some reason it doesn't actually go through each iteration of "i", specifically in this line:
spaces[i]=spaces[i]+randnum;
I know this because I put in printf statements to display the value of spaces[i] before and after; the first iteration of i works fine...but the second iteration actually uses spaces[i-1] instead and adds the randnum to that value?
And then, like I said, it crashes after one or two times of this...:-(
I know it's a lot but I'm hoping someone more experienced than I could spot the error(s) in this code for me! Please help!
I believe the first user above was correct in saying that the error is because there is no initial size declared for the array, but the solution is incorrect. You would have to allocate its size dynamically using malloc.
Also, I'd shorten spaces[i]=spaces[i]+randnum to just spaces[i] += randnum.
regarding: Problem is every time I run this code I get an error message that says "segmentation fault: 11" and I'm not sure what that means.
This means your program is trying to access memory that the application does not own.
For instance, a 'wild' pointer or uninitialized pointer or writing past the end of an array.
Thanks for the help. After a ton of tinkering around with this code I finally found the issue.
I was passing randnum to the speedmod function as if it were an index of the array spaces. I changed the function to the following, where num is the random number generated and go is the index:
void speedmod(struct car cars[4], int spaces [], int num, int go)
{
/* Declare pointer. */
int *spacesptr=spaces;
/* If the number of spaces plus the speed modifier is less than or equal to ten... */
if (num+cars[go].speedmod<=10)
{
/* ...add the speed modifier to the number of spaces moved. */
spaces[go]+=cars[go].speedmod;
}
}
Works perfectly now. Thanks for the help again.
you declare spaces[]={}, so it allocates a ptr that points to nothing. then you start writing all over it, which destroys probably your stack, your other variables, and whatever else is there -> undefined behavior.
you need to provide the memory to write to before you use it, for example spaces[1000]={}, ot however much you need.
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.
Using associative arrays implented via the POSIX hcreate/hsearch functions (as described here, I struggled some unexpected behaviour finding keys I've never entered or the other way around.
I tracked it down to some instance of store-by-reference-instead-of-value.
This was surprising to me, since in the example uses string literals as keys:
store("red", 0xff0000);
store("orange", 0x123456); /* Insert wrong value! */
store("green", 0x008000);
store("blue", 0x0000ff);
store("white", 0xffffff);
store("black", 0x000000);
store("orange", 0xffa500); /* Replace with correct value. */
Here is an MWE that shows my problem:
#include <inttypes.h> /* intptr_t */
#include <search.h> /* hcreate(), hsearch() */
#include <stdio.h> /* perror() */
#include <stdlib.h> /* exit() */
#include <string.h> /* strcpy() */
void exit_with_error(const char* error_message){
perror(error_message);
exit(EXIT_FAILURE);
}
int fetch(const char* key, intptr_t* value){
ENTRY e,*p;
e.key=(char*)key;
p=hsearch(e, FIND);
if(!p) return 0;
*value=(intptr_t)p->data;
return 1;
}
void store(const char *key, intptr_t value){
ENTRY e,*p;
e.key=(char*)key;
p = hsearch(e, ENTER);
if(!p) exit_with_error("hash full");
p->data = (void *)value;
}
void main(){
char a[4]="foo";
char b[4]="bar";
char c[4]="";
intptr_t x=NULL;
if(!hcreate(50)) exit_with_error("no hash");
store(a,1); /* a --> 1 */
strcpy(c,a); /* remember a */
strcpy(a,b); /* set a to b */
store(a,-1); /* b --> -1 */
strcpy(a,c); /* reset a */
if(fetch(a,&x)&&x==1) puts("a is here.");
if(!fetch(b,&x)) puts("b is not.");
strcpy(a,b); printf("But if we adjust a to match b");
if(fetch(a,&x)&&x==-1&&fetch(b,&x)&&x==-1) puts(", we find both.");
exit(EXIT_SUCCESS);
}
Compiling and executing above C code results in the following output:
a is here.
b is not.
But if we adjust a to match b, we find both.
I will need to read a file and store a a large number of string:int pairs and then I will need to read a second file to check an even larger number of strings for previously stored values.
I don't see how this would be possible if keys are compared by reference.
How can I change my associative array implementation to store keys by value?
And if that's not possible, how can I work around that problem given the above use case?
edit:
This question just deals with keys entered but not found.
The opposite problem also appears and is described in detail in this question.
edit:
It turned out that store() needs to strdup() key to fix this and another problem.
I found out that by using the same variable for storage & lookup, I can actually retrieve all the values in the array:
void main(){
char a[4]="foo";
char b[4]="bar";
char c[4]="baz";
char t[4]="";
intptr_t x=NULL;
if(!hcreate(50)) exit_with_error("no hash");
strcpy(t,a); store(t, 1); /* a --> 1 */
strcpy(t,b); store(t,-1); /* b --> -1 */
strcpy(t,c); store(t, 0); /* c --> 0 */
if(!fetch(a,&x)) puts("a is not here.");
if(!fetch(b,&x)) puts("Neither is b.");
if( fetch(c,&x)) puts("c is in (and equal to t).");
strcpy(t,a); if(fetch(t,&x)&&x== 1) puts("t can retrieve a.");
strcpy(t,b); if(fetch(t,&x)&&x==-1) puts("It also finds b.");
strcpy(t,c); if(fetch(t,&x)&&x== 0) puts("And as expected c.");
exit(EXIT_SUCCESS);
}
This results in the following output:
a is not here.
Neither is b.
c is in (and equal to t).
t can retrieve a.
It also finds b.
And as expected c.
However, I still don't understand why this is happening.
Somehow it seems the key needs to be at the same location (reference) and contain the same content (value) to be found.
I am required to create 6 threads to perform a task (increment/decrement a number) concurrently until the integer becomes 0. I am supposed to be using only UNIX commands (Pipelines to be specific) and I can't get my head around how pipelines work, or how I can implement this program.
This integer can be stored in a text file.
I would really appreciate it if anyone can explain how to implement this program
The book is right, pipes can be used to protect critical sections, although how to do so is non-obvous.
int *make_pipe_semaphore(int initial_count)
{
int *ptr = malloc(2 * sizeof(int));
if (pipe(ptr)) {
free(ptr);
return NULL;
}
while (initial_count--)
pipe_release(ptr);
return ptr;
}
void free_pipe_semaphore(int *sem)
{
close(sem[0]);
close(sem[1]);
free(sem);
}
void pipe_wait(int *sem)
{
char x;
read(sem[0], &x, 1);
}
void pipe_release(int *sem)
{
char x;
write(sem[1], &x, 1);
}
The maximum free resources in the semaphore varies from OS to OS but is usually at least 4096. This doesn't matter for protecting a critical section where the initial and maximum values are both 1.
Usage:
/* Initialization section */
int *sem = make_pipe_semaphore(1);
/* critical worker */
{
pipe_wait(sem);
/* do work */
/* end critical section */
pipe_release(sem);
}