【问题标题】:Segmentation fault while using malloc使用 malloc 时出现分段错误
【发布时间】:2017-06-06 10:31:20
【问题描述】:

作为一个练习,我正在尝试使用二叉搜索树!

我已经创建了代码,它似乎可以运行,但是当我尝试添加客户时它崩溃了。调试代码后,我在第 82 行遇到分段错误,我尝试将内存分配给根...研究了一段时间,我发现它与内存有关,但无法弄清楚我的代码发生了什么...关于尝试分配内存时导致此失败的原因有什么建议吗?

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

#define MAX_STRING 50

void flush();

struct customer {
    char *name;
    char *address;
    char *email;
};

struct double_linked_list {
    struct customer *data;
    struct double_linked_list *previous;
    struct double_linked_list *next;
};

struct double_linked_list *customers_head = 0;

struct BST_node {
    struct double_linked_list *data;
    struct BST_node *left;
    struct BST_node *right;
};

struct BST_node *BST_email_root = 0;

struct BST_node *BST_find_customer(struct BST_node *root, char *email) {
    if (root == NULL)
        return NULL;
    if (strcmp(email, root->data->data->email) == 0)
        return root;
    else {
        if (strcmp(email, root->data->data->email) == -1)
            return BST_find_customer(root->left, email);
        else
            return BST_find_customer(root->right, email);
    }
}

void find_customer() {
    char email[MAX_STRING];
    struct double_linked_list *l;
    struct BST_node *b;

    printf("Give the email of the customer (up to %d characters) : ", MAX_STRING - 1);
    gets(email);

    b = BST_find_customer(BST_email_root, email);
    if (b == 0)
        printf("There is no customer with this email.\n");
    else {
        l = b->data;
        printf("Customer found! \n");
        printf("Name    : %s\n", l->data->name);
        printf("Address : %s\n", l->data->address);
        printf("Email   : %s\n", l->data->email);
    }
}

struct BST_node *new_BST_node(struct BST_node *root, struct double_linked_list *l) {
    if (root == NULL);
    {
        root = (struct BST_node *)malloc(sizeof(struct BST_node));
        if (root == NULL) {
            printf("Out of Memory!");
            exit(1);
        }
        root->data = l;
        root->left = NULL;
        root->right = NULL;
    }

    if (strcmp(l->data->email, root->data->data->email) == -1)
        root->left = new_BST_node(root->left, l);
    else 
        root->right = new_BST_node(root->right, l);
    return root;
};

struct double_linked_list *new_customer() {
    char name[MAX_STRING], address[MAX_STRING], email[MAX_STRING];
    struct BST_node *b;
    struct double_linked_list *l;
    struct customer *c;

    printf("\nADDING NEW CUSTOMER\n=\n\n");
    printf("Give name (up to %d characters): ", MAX_STRING - 1);
    gets(name);

    printf("Give address (up to %d characters): ", MAX_STRING - 1);
    gets(address);

    printf("Give email (up to %d characters): ", MAX_STRING - 1);
    gets(email);

    b = BST_find_customer(BST_email_root, email);
    if (b) {
        printf("Duplicate email. Customer aborted.\n");
        return 0;
    }

    c = (struct customer *)malloc(sizeof(struct customer));
    if (c == 0) {
        printf("Not enough memory.\n");
        return 0;
    }

    c->name = strdup(name); // check for memory allocation problem
    if (c->name == 0)
        return 0;
    c->address = strdup(address);   // check for memory allocation problem
    if (c->address == 0)
        return 0;
    c->email = strdup(email);   // check for memory allocation problem
    if (c->email == 0)
        return 0;

    l = (struct double_linked_list*)malloc(sizeof(struct double_linked_list));
    if (l == 0) {
        printf("Not enough memory.\n");
        free(c->name);
        free(c->address);
        free(c->email);
        free(c);
        return 0;
    }

    l->data = c;
    l->previous = 0;
    l->next = customers_head;

    if (customers_head)
        customers_head->previous = l;

    customers_head = l;

    BST_email_root = new_BST_node(BST_email_root, l);

    return l;
}

void displaymenu() {
    printf("\n\n");
    printf("1. New customer\n");
    printf("2. Find customer using email\n");
    printf("0. Exit\n\n");
    printf("Give a choice (0-6) : ");
}

void flush() {
    char ch;
    while ((ch = getchar()) != '\n' && ch != EOF);
}

int main() {
    int choice;
    do {
        displaymenu();
        scanf("%d", &choice);
        flush();
        switch (choice) {
          case 1:
            new_customer();
            break;
          case 2:
            find_customer();
            break;
        }
    } while (choice != 0);

    return 0;
}

代码块调试器提供以下信息

活动调试器配置:GDB/CDB 调试器:默认

构建以确保源是最新的

选择目标:

调试 添加源目录:C:\debug\

添加源目录:C:\debug\

添加文件:C:\debug\bin\Debug\debug.exe

将目录更改为:C:/debug/。

设置变量:PATH=.;C:\Program Files\CodeBlocks\MinGW\bin;C:\Program Files\CodeBlocks\MinGW;C:\Windows\System32;C:\Windows;C:\Windows\System32 \wbem;C:\Windows\System32\WindowsPowerShell\v1.0;C:\Program Files\ATI Technologies\ATI.ACE\Core-Static;C:\Users\baskon\AppData\Local\Microsoft\WindowsApps

启动调试器:C:\Program Files\CodeBlocks\MINGW\bin\gdb.exe -nx -fullname -quiet -args C:/debug/bin/Debug/debug.exe

完成

注册的新类型:wxString

注册的新类型:STL String

注册新类型:STL Vector

设置断点

调试器名称和版本:GNU gdb (GDB) 7.6.1

子进程PID:5908

程序收到信号SIGSEGV,分段错误。

在?? () ()

C:\debug\main.c:82 的 new_BST_node (root=0x0, l=0xbe0ec8) 中的 9 0x00401480 C:\debug\main.c:82:1907:beg:0x401480

在 C:\debug\main.c:82

C:\debug\main.c:82 的 new_BST_node (root=0x0, l=0xbe0ec8) 中的 9 0x00401480 C:\debug\main.c:82:1907:beg:0x401480

调用栈如下

【问题讨论】:

  • 分段错误,使用malloc() 时永远不会发生。另外,让您的代码呼吸。
  • 感谢您的建议,我认为现在我的代码更具可读性。这就是调试器的建议。第 82 行中的分段错误,我在其中分配内存!
  • @ritgeo 你能包括调用堆栈吗?此外,在调试之前,请确保生成调试信息以使调试更容易(GCC 上的-g 标志)。
  • 我从 Codeblocks 调试器上传了所有信息,希望对您有所帮助!谢谢!
  • 请修正缩进。代码很难阅读。另外,这真的是产生问题的最小代码吗?见minimal reproducible example

标签: c segmentation-fault


【解决方案1】:

您的代码中存在多个问题:

  • 这里有一个经典的错误:

    struct BST_node *new_BST_node(struct BST_node *root, struct double_linked_list *l) {
    if (root == NULL);
    {
        root = (struct BST_node *)malloc(sizeof(struct BST_node));
    

    if 语句行末尾的; 被解析为空语句。由{ 引入的后续块将始终被执行。

    您可以避免这种愚蠢的错误,方法是始终在复合语句中使用大括号并将它们放在语句开头的同一行,不是在下一行。这与 40 多年前 C 语言的创造者所使用的原始 K&R 风格接近。

  • 函数flush中变量ch的类型应该是int,以便正确区分getc()返回的所有值:unsigned char的所有值加上特殊值EOF

     void flush(void) {
        int ch;
        while ((ch = getchar()) != EOF && ch != '\n') {
            continue;
        }
    }
    

    请注意,您应该像我在上面所做的那样使空语句更明确,以避免混淆和错误,如前一个。

  • 您不应使用过时的不安全函数gets():使用fgets() 并用strcspn() 去除尾随换行符。

  • 当用strcmp()比较字符串时,你应该只依赖返回值的符号。在函数BST_find_customer()new_BST_node() 中,您与-1 进行比较:这是不可靠的。请改用if (strcmp(email, root-&gt;data-&gt;data-&gt;email) &lt; 0)

  • 在函数new_BST_node() 中,在树中创建新节点时不会返回root。这是一个更正的版本:

    struct BST_node *new_BST_node(struct BST_node *root, struct double_linked_list *l) {
        if (root == NULL) {
            root = malloc(sizeof(*root));
            if (root == NULL) {
                printf("Out of Memory!");
                exit(1);
            }
            root->data = l;
            root->left = NULL;
            root->right = NULL;
            return root;
        }
    
        if (strcmp(l->data->email, root->data->data->email) < 0) {
            root->left = new_BST_node(root->left, l);
        } else {
            root->right = new_BST_node(root->right, l);
        }
        return root;
    }
    

    请注意,这会导致您的错误,因为您可能在这里有无限递归。

  • 最后几点建议:

    • 在将指针与空指针进行比较时,使用NULL 而不是0。它更具可读性。
    • 避免将变量命名为l,因为该名称在图形上与编程环境中使用的固定间距字体1 过于接近。有时它几乎无法区分。

【讨论】:

  • 谢谢!我看到最好的办法是使用 0 作为 strcmp.. 还修复了 ;错误.. 但是为什么如果我说.. 如果 strcmp 0?
  • @ritgeo:阅读我的最新更新。不返回分配的root 导致无限递归。
【解决方案2】:

好的,所以在测试完所有内容后,我发现了问题所在但我不知道为什么.. 有什么建议吗?? 我认为 strcmp 返回 0 或 -1 或 1 的值。 但是有一个问题,如果我没有准确定义如果 strcmp ==1 或如果 strcmp ==-1 ...我似乎有 无限循环 (我使用 printf 命令查看发生了什么,我发现了这个错误..)

通过改变

struct BST_node *new_BST_node(struct BST_node *root, struct double_linked_list *l)
{
if (root==NULL)
    {
    root = (struct BST_node *) malloc (sizeof(struct BST_node ));
    if (root==NULL)
        {
        printf("Out of Memory!");
        exit(1);
        }
    root->data=l;
    root->left=NULL;
    root->right=NULL;
    }

    if (strcmp(l->data->email, root->data->data->email) == -1)
        root->left =new_BST_node(root->left,l);
    else 
        root->right =new_BST_node(root->right,l);

    return root;
};

struct BST_node *new_BST_node(struct BST_node *root, struct double_linked_list *l)
    {
    if (root==NULL)
        {
        root= (struct BST_node *)malloc(sizeof(struct BST_node ));
        if (root==NULL)
            {
            printf("Out of Memory!");
            exit(1);
            }

        root->data=l;
        root->left=NULL;
        root->right=NULL;
        }

    if ((strcmp(l->data->email, root->data->data->email))==-1)
                root->left =new_BST_node(root->left,l);
    else if ((strcmp(l->data->email, root->data->data->email)) ==1)
        root->right =new_BST_node(root->right,l);

    return root;
};

一切正常.. 但为什么其他代码不起作用?我很确定它是一样的...

【讨论】:

  • Breath,意味着l-&gt;data-&gt;email,root-&gt;data-&gt;data-&gt;email 看起来也和l-&gt;data-&gt;email-&gt;root-&gt;data-&gt;data-&gt;email 完全一样,像这样链接指针真的很糟糕。它不可读,可能会导致调试器无法帮助您找到的问题。
  • 感谢 Iharob 的建议!修复了我的问题的解决方案,希望它比以前更具可读性..
  • 另外,你不能像这样依赖strcmp() 的返回值。请改用!= 0
猜你喜欢
  • 2018-09-24
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
  • 2018-09-11
  • 2022-01-20
  • 1970-01-01
  • 2022-01-13
相关资源
最近更新 更多