2010-04-18 107 views
2

main.c中(與像標準輸入輸出,STDLIB,等所有的頭):程序執行在scanf處停止?

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_ */ 

我使用Eclipse CDT的,當我輸入1,然後,我輸入一個密鑰。然後控制檯說。我用gdb並得到這個錯誤:

Program received signal SIGSEGV, Segmentation fault. 
0x00177024 in _IO_vfscanf() from /lib/tls/i686/cmov/libc.so.6 

任何想法爲什麼?

+2

A推薦。不要將字符串typedef char *。將它保留爲char *應該可以幫助你記住,在使用它們之前,你必須爲每一個分配內存。 – 2010-04-18 15:51:49

+0

剛纔改變了。 – 2010-04-18 16:05:45

回答

5

應該分配您的字符串足夠的內存(的typedef的char *字符串)讀取與scanf()的

+0

謝謝!我是C新手,我完全忘了! – 2010-04-18 16:04:54

0

嗯,你確定scanf函數可以使用提供的字符串來存儲數據?

我會嘗試使用字符緩衝區足夠大,或切換到真正的C++函數讀取輸入。

2

你必須來分配scanf()會調用它之​​前使用的所有存儲; scanf()不分配存儲空間。你的字符串是空的;爲這些值分配的存儲空間最小。輸入任何額外的數據都是一場災難。

另外,scanf()的期望的字符指針,而不是字符串引用或值 - 因爲它是一個可變參數函數,僅存在警告,編譯器可以做的一個有限的量。

3
  • 喜歡喬納森&帕特里克說,分配存儲器第一,然後再通過指針/陣列SCANF。

//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];

你也可能要簽上我有在這裏GDB小演練:

>2600Hertz/Hacking-into-any-executable-using-gdb/

好運!

CVS @ 2600Hertz