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

C语言反转字符串出现Segmentation Fault (Core Dumped)问题求助

排查字符串反转打印的Segmentation Fault错误

问题根源

在4-print_rev.c的print_rev函数中,变量i未初始化:

int i; // 未初始化,值为随机垃圾值
while (s[i] != '\0') {
    i++;
}

Linux沙箱环境下,未初始化的栈变量会被赋予随机值,导致第一次while循环直接访问字符串数组范围外的内存,触发Segmentation Fault。部分在线编译器可能默认将未初始化栈变量初始化为0,因此巧合能正常运行,但这属于未定义行为,完全不可依赖。

修复方案

给变量i初始化为0,确保从字符串第一个字符开始遍历:

#include "main.h"

/**
 * print_rev - prints a string in reverse
 * @s: the string to be printed
 */
void print_rev(char *s)
{
        int i = 0; // 初始化i为0

        while (s[i] != '\0')
        {
                i++;
        }
        while (i > 0)
        {
                _putchar(s[i-1]);
                i--;
        }
        _putchar('\n');
}

额外验证点

确保你已正确实现_putchar函数(用户代码未提供该实现,缺失会导致运行错误),标准实现示例:

#include "main.h"
#include <unistd.h>

int _putchar(char c)
{
        return write(1, &c, 1);
}

内容的提问来源于stack exchange,提问作者Akintola Oluwaseyi Alex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 10:17:23