【问题标题】:Segmentation fault error (c), I don't know what's wrong?Segmentation fault 错误(c),不知道怎么回事?
【发布时间】:2020-06-11 19:35:21
【问题描述】:

我不断收到分段错误错误,我似乎找不到问题所在。

一个例子是:

输入:4 bbbb

输出:2 abab

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

int main() {
    int a, len, i = 0, count = 0;
    scanf("%d", &a);
    len = a;
    char *strn = malloc((len * sizeof(char*)) + 1);
    scanf("%s", strn);

    while (i != len) {
        if (strn[i]=='a' && strn[i+1]=='a') {
            strn[i] = 'b';
            count++;
            i++;
        } else if (strn[i]=='b' && strn[i+1]=='b') {
            strn[i] = 'a';
            count++;
            i++;
        } else {
            i+=2;
        }
    }

    printf("%d\n%s\n", count, strn);
    free(strn);
    return 0;
}

【问题讨论】:

  • ??????小心前行,看看会发生什么?
  • 您的意思可能是sizeof(char) 或基本上是1,而不是sizeof(char*),它是系统上指针的大小。
  • 我认为您需要while (i &lt; len-1),因为i 可能会比len 更大而永远不会相等,并且您正在访问i 之外的一个。
  • 输入字符串后应设置len = strlen(strn);
  • 弗雷德,谢谢!我的错误与 while 循环条件有关。

标签: c memory-leaks segmentation-fault


【解决方案1】:

对于初学者来说这个内存分配

char *strn = malloc((len * sizeof(char*)) + 1);
                                  ^^^^^^

不正确。

看来你的意思

char *strn = malloc((len * sizeof(char)) + 1);

循环中的条件

while (i != len) {

可以调用未定义的行为,因为变量 i 的值可以绕过与变量 len 中的值相等的值,因为 else 语句

    } else {
        i+=2;
    }

并使用表达式i + 1 作为索引,因为例如当i 等于3 然后strn[i + 1] 等于终止零'\0' 并且将执行else 语句,这将增加@ 987654332@2

你可以像这样重写while语句

while (i + 1 < len) {

【讨论】:

    猜你喜欢
    • 2022-11-01
    • 2018-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多