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; }
关键修改说明
- 替换错误的手动复制逻辑:用标准库
strcpy实现数组内容复制,既简洁又避免下标错误;若坚持手动循环,需改为:for (int j = 0; j < index; j++) { sentence[j] = reverse[j]; } sentence[index] = '\0'; - 用
strlen替代自定义my_strlen,减少冗余代码; - 简化
main输出逻辑,直接使用printf("%s\n", sentence)打印结果,无需逐个字符遍历。
内容的提问来源于stack exchange,提问作者strugglingcsstudent
相关产品推荐
相关产品推荐

