首页 文章

我的程序正在生成分段错误

提问于
浏览
-5

该方法正在生成分段错误 . 该方法旨在返回列表的指定位置的值 . 该列表是多项式列表 . 它应该返回一个多项式 . 我尝试使用gdb,但它只是告诉我它是什么方法 .

llink* get_specific(llist* node)
{
    struct link * poly;
    int i;
    printf("Which polynomial do you want: ");
    scanf("%d",&i);
    llist* current;
    current = node;
    int j;
    llist* temp;
    for (j = 1;j < i;j++)
        current = current->next;
    poly = current->poly;
  return poly;
}

编辑:用j修复错误并且不再分配内存后,这段代码第一次正常运行但如果我第二次运行它会出错

EDIT2:

for (j = 1;j < i;j++)
        current = current->next;

当访问for循环内部的行时,会导致分段错误 . 如果用户输入为1,则运行正常,但如果是其他任何内容则出现故障

4 回答

  • 2
    • NULL 检查 llist* node

    • 无需分配 llist* current [ llist* current = malloc(sizeof(llist)); ]

    • for (j == 1;j < i;j++) 应为 for (j = 0;j < i;j++)
      在解除引用之前

    • ,在 current->next; 中检查 NULL for current

    注意:不要转换 malloc() 的返回值 .

  • 2

    for (j == 1;j < i;j++)

    应该是

    for (j = 1; j < i; j++)

  • 1

    您的代码有内存泄漏 .

    例如,您分配一个节点但不使用它,并且不释放内存

    llist* current = malloc(sizeof(llist));
    current = node;
    

    写函数更简单

    llink * get_specific( const llink *node )
    {
        size_t i;
    
        printf( "Which polynomial do you want: " );
        scanf( "%u", &i );
    
        while ( node != NULL && i-- ) node = node->next;
    
        return node;
    }
    

    您的代码中还有三种不同的类型: linkllinkllist . 我不知道他们的意思所以我在我的函数中只使用了一种类型llink . 至少它指出了如何编写函数的正确方向 . :)

  • 3

    您的代码有几个问题 . 我怀疑分段错误是因为你没有初始化你的 j 变量 . for 循环中的initialisation子句实际上是一个比较运算符 . 它应该是 j = 1 (或可能是 j = 0 )而不是 j == 1 .

    如果用户输入的数字超过列表的末尾,也可能发生故障 . 你需要在循环中进行某种测试,以确保你不会超出范围 .

    看起来你实际上需要那些 malloc 来电 . 你没有分配(并且你也没有释放它,所以它会泄漏) .

相关问题