You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言输入字符串与子串并移除子串时出现段错误问题

段错误原因及修复方案

核心问题分析

  • 未初始化野指针:char *s 和 const char *r 都是未初始化的指针,没有指向任何有效的内存区域。scanf 尝试向这些未知地址写入数据,直接触发段错误。
  • scanf格式符错误:%[^\n]s 中的末尾s是多余的,正确格式符应为%[^\n];此外第一次输入后的换行符会留在缓冲区,导致第二次scanf直接读取空字符串。
  • const指针不可写入:const char *r 声明为只读指针,无法通过scanf向其指向区域写入数据。

修复后的代码

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

void removeSubstring(char *s, const char *r) {
    int len = strlen(r);
    char *pos;

    while ((pos = strstr(s, r)) != NULL) {
        memmove(pos, pos + len, strlen(pos + len) + 1);
    }
}

int main() {
    // 用固定大小数组分配内存,也可根据需求用malloc动态分配
    char s[1000];
    char r[200];

    printf("Enter the first string: ");
    // 读取字符串并忽略开头空白,%[^\n]读取到换行符为止
    scanf(" %[^\n]", s);
    // 清除输入缓冲区的换行符
    getchar();

    printf("Enter the second string: ");
    scanf(" %[^\n]", r);

    removeSubstring(s, r);

    printf("Modified string: %s\n", s);

    return 0;
}

额外说明

  • 如果需要处理更长的字符串,建议使用malloc动态分配内存,示例如下:
    char *s = malloc(1000 * sizeof(char));
    if (s == NULL) {
        perror("malloc failed");
        return 1;
    }
    // 使用完成后记得调用free(s);释放内存
    
  • removeSubstring函数本身逻辑正确,memmove能妥善处理内存重叠场景,适合字符串内部的内容移动操作。

内容的提问来源于stack exchange,提问作者Alberto Mura

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 12:13:15