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
相关产品推荐
相关产品推荐

