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

C语言实现deblank函数时触发zsh bus error问题求助

问题分析与修复方案

核心错误原因

deblank函数里的计数变量o未初始化,它的初始值是内存中的随机垃圾值。执行outstr[o] = inpstr[i]时,相当于访问了不确定的内存地址,直接触发内存越界,导致zsh bus error。

其他潜在问题

  1. 处理完成后,outstr未添加字符串终止符'\0',后续打印或使用该字符串时会出现乱码或未定义行为。
  2. chomp函数未处理空字符串场景:若输入字符串长度为0,strlen(word)-1会得到-1,访问word[-1]会触发数组越界。

修复后的完整代码

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

// 提前声明函数原型
void chomp(char word[]);
void deblank(char *inpstr, char *outstr);

int main()
{
    char inpstr[20];
    char outstr[20];
    printf("Enter a string: ");
    fgets(inpstr, 20, stdin);
    chomp(inpstr);

    deblank(inpstr, outstr);
    // 测试打印处理后的字符串
    printf("Result: %s\n", outstr);

    return 0;
}

void chomp(char word[])
{
    // 先判断字符串长度是否大于0,避免越界
    size_t len = strlen(word);
    if(len > 0 && word[len - 1] == '\n')
    {
        word[len - 1] = '\0';
    }
}

void deblank(char *inpstr, char *outstr)
{
    int length = strlen(inpstr);
    // 初始化计数变量o为0
    int o = 0;

    for(int i = 0; i < length; i++)
    {
        if(inpstr[i] != ' ')
        {
            outstr[o] = inpstr[i];
            o++;
        }
    }
    // 添加字符串终止符,确保outstr是合法的C字符串
    outstr[o] = '\0';
}

修复点说明

  • 给deblank里的o初始化为0,确保从outstr的第一个位置(索引0)开始写入。
  • 在deblank循环结束后,给outstr加上'\0',标记字符串结束。
  • 修改chomp函数,先获取字符串长度并判断是否大于0,再处理换行符,避免数组越界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:53:31