【问题标题】:Bus 10 error with recursive call递归调用的总线 10 错误
【发布时间】:2015-04-15 21:44:54
【问题描述】:

所以我遇到了这个递归函数调用的问题...... 我正在尝试编写一个函数来检查我的结构中的每个字符串是否遵循字母顺序,如果是,它将返回 1,如果不是,它将返回 0。

我不断收到总线 10 错误,我尝试将打印语句/找不到我的错误在哪里。 任何人都可以帮忙吗? 谢谢。

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

typedef struct string_list string_list;
struct string_list {
  char *val;
  string_list *next;
};

int sl_sorted_asc(string_list *ss) {

 int  string_c = strcmp(ss->val, ss->next->val);
 if (string_c >= 0) {
   if (ss->next != NULL) {
   sl_sorted_asc(ss->next);
   }
   else {
     return 1;
   }
 }
 else  {
   return 0;
 }
 return 1;
}

int main() {

  string_list hi;
  hi.val = "Leeho";
  hi.next->val = "Ferris";
  hi.next->next->val = "Donny";

printf("%d\n", sl_sorted_asc(&hi));

}

【问题讨论】:

  • 您正在通过main() 的第三行和第四行的无效指针写入。
  • 建议不要用诸如:'typedef struct string_list string_list;'之类的废话来混淆代码、编译器名称空间等相反,在代码中需要引用结构名称的每个点,简单地说“struct string_list”
  • 关于“编码风格”:为了那些必须阅读/调试/修改/维护您的代码的人(包括您自己)强烈建议不要使用“乔治亚”风格的大括号(眼睛效果很好垂直方向,但不是当它必须不断地向左/向右跳转以找到匹配的大括号时)和一致的缩进量(当使用非等宽字体时,2个空格不足以清楚地显示缩进。建议始终使用4个空格缩进)跨度>

标签: c string recursion struct


【解决方案1】:

代码引用了未分配的内存

例如在以下几行中:

// allocates one instance of the struct on the stack
string_list hi;    

// sets the 'val' field of the instance of the struct on the stack
hi.val = "Leeho";    

// follows a non-initialized pointer, 
// in the instance of the struct on the stack,
// to a non allocated instance of the struct
// then writes on that non allocated instance of the struct
// I.E. writes to random memory address
hi.next->val = "Ferris";   

// follows a non-initialized pointer
// contained in a non allocated instance of the struct
// to a non allocated instance of the struct
// then writes on that non allocated instance of the struct  
// I.E. follows random values in memory 
//      to some random location in memory
//      then writes on an offset to that random location           
hi.next->next->val = "Donny";

【讨论】:

    【解决方案2】:

    (必须链接到http://ericlippert.com/2014/03/05/how-to-debug-small-programs/

    要解决这样的问题,有一个名为 valgrind 的程序非常宝贵(例如,如果您的操作系统不支持它,请立即获取虚拟机!);例如在这种情况下它报告 ==3637== Use of uninitialised value of size 8 ==3637== at 0x4005BE: main (bus10.c:33)

    第 33 行是“hi.next->val = ...”;问题(在 this 行中 - 它是唯一的地方吗?)是,你从未做过“hi.next = ...”,所以 hi.next 指向...什么? 基本上,任何东西 - 当堆栈增长为 hi 变量腾出空间时, hi.next 将占用其中的任何位,这意味着它可以指向几乎任何东西(包括它自己,不存在的内存地址 - 你的名字它)。

    TLDR:永远,永远使用您未初始化的变量(除非您希望专家 C 程序员向您讲解“未定义行为”和朋友)

    【讨论】:

      【解决方案3】:

      可能是因为在你的 sl_sorted_asc 函数的这一行

       int  string_c = strcmp(ss->val, ss->next->val);
      

      您不是首先检查 ss->next 是否为空。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-14
        • 1970-01-01
        • 2017-07-06
        • 2013-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多