【问题标题】:Unable to find the segmentation fault无法找到分段错误
【发布时间】:2017-04-26 10:59:09
【问题描述】:

我需要帮助理解的内容:

我正在尝试了解我遇到的分段错误:

分段错误(核心转储)

从查看 SO 和 Google 来看,这似乎与尝试访问代码在某些范围内无法访问的内存有关。但是我似乎无法弄清楚它发生在哪里。

我正在尝试做什么(期待):

我正在学习 C 编程语言并尝试解决练习 2.4:squeeze(s1, s2) - 在 s1 中删除 s2 中的所有字符实例。

我还没有接触到动态数组等,所以我只能“能够”(从最温和的意义上说)使用简单的原始数据类型。不过,我有使用高级语言的经验!

我做了什么:

我在 Windows 10 机器上运行 CygWin,编译器 (gcc) 没有问题。

这是我为解决上述问题而编写的代码:

/*
    Exercise 2.4
    squeeze (s1, s2): Remove all characters of s2 in s1.
    INPUT : s1.length >= s2 > 0.
    OUTPUT: The rest of s1 after deleting all occurances of letters in s2.
*/

#include <stdio.h>

void squeeze (char s1[], const char *s2);  /* Returns (by-ref) the resulting string s1 after removing all occurences of s2. */
int toUpper(char c);                      /* returns the numerical representation of a hexadecimal digit. */

int main () {
    char s1[] = "I am a test.\0";
    const char *s2 = "AE\0";
    printf("Before manipulation: %s\n", s1);
    squeeze(s1, s2);
    printf("After manipulation:  %s", s1);
}

/*
    Returns the (by-ref) resulting string s1 after removing all occurences
    of letters in s2.
*/

void squeeze (char s1[], const char *s2) {
    int index, s2_index, c = 0;

    while (s1[index] != '\0') {
        while(s2[s2_index] != '\0') {
            if ((c = toUpper(s1[index])) == s2[s2_index]){
                s1[index] = s1[index + 1];
            }
            s2_index++;
        }
        s2_index = 0;
        index++;
    }
}
/*
    Returns the upper-case representation of char c.
*/

int toUpper (char c) {
    if (c >= 'a' && c <= 'z')
        return c - 32;
    else
        return c;
}

干杯!如果您有任何问题或我遗漏了什么,请随时发表评论! :)

感谢您的帮助!

【问题讨论】:

  • indexs2_index 未初始化。
  • 这真的很好奇。它解决了我的问题。但现在我很困惑。那个语法不是应该意味着c = 0, s2_index = c and index = s2_index吗?
  • 不,不是。如果能这样工作就好了。
  • 哈哈。我的错。一定是书上看错了。感谢您的澄清! :)
  • 它几乎是重复的:stackoverflow.com/q/6838408/4996248(尽管 C++ 和 C 不是同一种语言,但它们在这里没有区别)。

标签: c arrays segmentation-fault


【解决方案1】:

永远不要在一行上写多个变量声明。这被认为是非常糟糕的做法,因为它更容易编写错误。 (坏书可能会传授这种风格,谨防坏书。)

int index, s2_index, c = 0;

与更具可读性的相同

int index;
int s2_index;
int c = 0;

从可读版本中我们可以看出,您只需将一个变量初始化为零。将代码更改为:

int index = 0;
int s2_index = 0;
int c = 0;

更好的是,您可以将循环去混淆成更易读的代码:

for(size_t i1=0; s1[i1] != '\0'; i1++)
{
  for(size_t i2=0; s2[i2] != '\0'; i2++)
  {
    ...
  }
}

您可能会注意到,您可能应该在每次复制某些内容时增加“索引”,而不是在循环中的每一圈(?)。

【讨论】:

    【解决方案2】:

    你需要初始化indexs2_index

    改变:

    int index, s2_index, c = 0;
    

    到:

    int index = 0, s2_index = 0, c = 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 2013-10-06
      • 2021-06-29
      • 2011-01-15
      相关资源
      最近更新 更多