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

C语言实现句子单词反转遇stack-buffer-overflow错误求助

C语言单词反转功能的栈溢出问题修复

核心错误点

  • 数组越界赋值触发栈溢出:最后将reverse内容复制回sentence的循环中,错误使用index作为数组下标而非循环变量j。原代码sentence[index] = reverse[index]中,index是字符串总长度,远超sentence的有效索引范围,直接导致栈缓冲区溢出。
  • 冗余代码:自定义的my_strlen功能与标准库strlen完全一致,可直接替换以简化代码。

修正后的代码

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

void reverse_words(char sentence[]) {
    int len = strlen(sentence);
    int word_start = len;
    int word_end = len;
    int index = 0;
    int i;
    char reverse[len + 1];

    while (word_start > 0) {
        if (sentence[word_start] == ' ') {
            i = word_start + 1;
            while (i <= word_end) {
                reverse[index++] = sentence[i++];
            }
            reverse[index++] = ' ';
            word_end = word_start - 1;
        }
        word_start--;
    }

    // 处理开头的第一个单词
    for (int j = 0; j <= word_end; j++) {
        reverse[index++] = sentence[j];
    }
    reverse[index] = '\0';

    // 正确复制反转结果回原数组
    strcpy(sentence, reverse);
}

int main(void) {
    char sentence[] = "abcd efgh ijkl mnop qrst uvxy z";
    reverse_words(sentence);
    printf("%s\n", sentence);
    return 0;
}

关键修改说明

  1. 替换错误的手动复制逻辑:用标准库strcpy实现数组内容复制,既简洁又避免下标错误;若坚持手动循环,需改为:
    for (int j = 0; j < index; j++) {
        sentence[j] = reverse[j];
    }
    sentence[index] = '\0';
    
  2. 用strlen替代自定义my_strlen,减少冗余代码;
  3. 简化main输出逻辑,直接使用printf("%s\n", sentence)打印结果,无需逐个字符遍历。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 11:30:57