【问题标题】:Segmentation fault after user input用户输入后的分段错误
【发布时间】:2017-02-15 02:52:22
【问题描述】:

下面我已将我的完整代码包含到我正在处理的程序中。它应该允许用户在程序中输入输入,直到他们输入“。”。在名字输入中。我在输入一次后遇到分段错误,一旦我第二次将输入输入到结构中,它就会让我出错。我还应该动态分配结构,以便用户可以根据需要多次输入输入,但为了测试,我将其设置为 10 以查看程序是否可以工作。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student {
    int recordCount;
    char *firstName;
    char *lastName;
    char *id;
    char *email;
};

int main()
{
    struct student *aPtr;

    aPtr = malloc(sizeof(struct student)*10);
    //aPtr = (struct student*) malloc(10 * sizeof(struct student));
    aPtr->firstName = malloc(sizeof(char)*50);
    aPtr->lastName = malloc(sizeof(char)*50);
    aPtr->id = malloc(sizeof(char)*10);
    aPtr->email = malloc(sizeof(char)*50);

    int i;
    for (i = 0; i < 10; ++i) {
        printf("First Name: ");
        scanf("%s", (aPtr + i)->firstName);
        if ((aPtr + i)->firstName[0] == '.') {
            break;
        }

        printf("Last Name: ");
        scanf("%s", (aPtr + i)->lastName);

        printf("ID#: ");
        scanf("%s", (aPtr + i)->id);

        printf("Email: ");
        scanf("%s", (aPtr + i)->email);


        printf("\n");
        aPtr->recordCount++;
    }

    for (i = 0; i < aPtr->recordCount; ++i) {
        printf("%s, %s, %s, %s",(aPtr + i)->id, (aPtr + i)->firstName, (aPtr + i)->lastName, (aPtr + i)->email);
        printf("\n");
    }

    return 0;
}

【问题讨论】:

  • 在调试器下运行你的程序。
  • 您只初始化了aPtr[0]的字段,但您正在尝试使用其中的10个字段。
  • 我建议声明 char firstName[50] 而不是 char *firstName。只需在每次需要时动态分配一个新的 struct Student,但不要为各种 struct 成员执行此操作。并以数组或链表的形式跟踪您分配的所有学生。最后,在退出 main 之前释放整个列表。
  • 您应该查看proper C formatting。或了解如何thoroughly obfuscate your code
  • @JsmileyJ 好吧,如果你打算使用它,你可能想弄清楚。 github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet

标签: c input struct segmentation-fault malloc


【解决方案1】:

使用gdb调试器调试你的代码,你可以自己找。 如果您不熟悉调试,请点击此链接了解更多信息。 https://www.tutorialspoint.com/gnu_debugger/index.htm

在这段代码中,我认为你在这一行中错误地使用了指针:

aPtr + i)->firstName[0] == '.'

纠正一下,查找指针的正确使用。

注意:您可以通过使用 char firstname[50]、lastname[50]、.....等来使您的代码更简单。使用它,你可以很容易地摆脱分段错误。

希望对您有所帮助!谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-19
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多