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;
}

存储.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

您应该为您的字符串(typedef char* string)分配足够的内存以使用 scanf() 读取

于 2010-04-18T14:58:11.873 回答
3
  • 就像 Jonathan & Patrick 所说,首先分配内存,然后将指针/数组传递给 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 上的一个小演练:

> 2600 赫兹/使用 gdb 侵入任何可执行文件/

祝你好运!!

CVS @ 2600 赫兹

于 2010-04-18T15:39:23.793 回答
2

您必须在调用它之前分配所有scanf()将要使用的存储空间;scanf()不分配存储。你的字符串是空的;为这些值分配的存储空间最少。输入任何额外的数据都是一场灾难。

另外,scanf() 需要一个字符指针,而不是字符串引用或值——因为它是一个可变参数函数,编译器只能发出有限的警告。

于 2010-04-18T14:58:44.470 回答
0

嗯,你确定 scanf 可以使用提供的字符串来存储数据吗?

我会尝试使用足够大的字符缓冲区或切换到真正的 C++ 函数来读取输入。

于 2010-04-18T14:56:31.807 回答