Reputation: 55227
main.c (with all the headers like stdio, stdlib, etc):
int main()
{
int input;
while(1)
{
printf("\n");
printf("\n1. Add new node");
printf("\n2. Delete existing node");
printf("\n3. Print all data");
printf("\n4. Exit");
printf("Enter your option -> ");
scanf("%d", &input);
string key = "";
string tempKey = "";
string tempValue = "";
Node newNode;
Node temp;
switch (input) {
case 1:
printf("\nEnter a key: ");
scanf("%s", tempKey);
printf("\nEnter a value: ");
scanf("%s", tempValue); //execution ternimates here
newNode.key = tempKey;
newNode.value = tempValue;
AddNode(newNode);
break;
case 2:
printf("\nEnter the key of the node: ");
scanf("%s", key);
temp = GetNode(key);
DeleteNode(temp);
break;
case 3:
printf("\n");
PrintAllNodes();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong option chosen!\n");
break;
}
}
return 0;
}
storage.h:
#ifndef DATABASEIO_H_
#define DATABASEIO_H_
//typedefs
typedef char *string;
/*
* main struct with key, value,
* and pointer to next struct
* Also typedefs Node and NodePtr
*/
typedef struct Node {
string key;
string value;
struct Node *next;
} Node, *NodePtr;
//Function Prototypes
void AddNode(Node node);
void DeleteNode(Node node);
Node GetNode(string key);
void PrintAllNodes();
#endif /* DATABASEIO_H_ */
I am using Eclipse CDT, and when I enter 1, then I enter a key. Then the console says . I used gdb and got this error:
Program received signal SIGSEGV, Segmentation fault.
0x00177024 in _IO_vfscanf () from /lib/tls/i686/cmov/libc.so.6
Any ideas why?
Upvotes: 2
Views: 4069
Reputation: 22497
//Change the value here to change the size of Ur strings (char-arrays actually)
#define MAX_LENGTH 20
char key[MAX_LENGTH];
char tempKey[MAX_LENGTH];
char tempValue[MAX_LENGTH];
You might also want to checkout a small walkthrough on gdb that i have over here:
GoodLUCK!!
CVS @ 2600Hertz
Upvotes: 3
Reputation: 754170
You have to allocate all the storage that scanf()
is going to use before you call it; scanf()
does not allocate storage. Your strings are empty; there is minimal storage allocated for the values. Entering any extra data is a disaster.
Plus, scanf() expects a character pointer, not a string reference or value - because it is a variadic function, there is only a limited amount of warning that the compiler can do.
Upvotes: 2
Reputation: 5935
you should allocate enough memory for your strings (typedef char* string) to read into with scanf()
Upvotes: 5
Reputation: 7958
Hmm, are you sure that scanf can use the provided string to store the data?
I'd try to use a char buffer that is large enough or switch to real C++ functions to read input.
Upvotes: 0