2

main.c (stdio、stdlib などのすべてのヘッダーを含む):

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

理由はありますか?

4

4 に答える 4

5

scanf() で読み取る文字列 (typedef char* 文字列) に十分なメモリを割り当てる必要があります。

于 2010-04-18T14:58:11.873 に答える
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 @ 2600ヘルツ

于 2010-04-18T15:39:23.793 に答える
2

scanf()呼び出す前に、使用するすべてのストレージを割り当てる必要があります。scanf()ストレージを割り当てません。あなたの文字列は空です。値に割り当てられる最小限のストレージがあります。余分なデータを入力するのは災害です。

さらに、scanf() は、文字列の参照や値ではなく、文字ポインターを想定しています。これは可変引数関数であるため、コンパイラーが実行できる警告の量は限られています。

于 2010-04-18T14:58:44.470 に答える
0

うーん、scanf が提供された文字列を使用してデータを格納できると確信していますか?

十分な大きさの char バッファーを使用するか、実際の C++ 関数に切り替えて入力を読み取ろうとします。

于 2010-04-18T14:56:31.807 に答える