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

LeetCode「最后一个单词的长度」运行时错误排查(输入"a"报错)

解决LeetCode「最后一个单词的长度」运行时错误问题

本地运行输入"a"时能得到正确输出,但在线提交触发堆缓冲区溢出错误,错误信息如下:

==22==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60200000008f at pc 0x55a501284db8 bp 0x7ffd0c0b9450 sp 0x7ffd0c0b9440
READ of size 1 at 0x60200000008f thread T0
#2 0x7f6a233ee082 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x24082)
0x60200000008f is located 1 bytes to the left of 2-byte region [0x602000000090,0x602000000092)

用户使用的代码:

int lengthOfLastWord(char *s){
    int count = 0;
    int len = strlen(s) -1;
    int templen = len;
    for (int i = len;s[i] == ' ';i--){
        templen--;
    }
    for (int i = templen; (s[i] != ' ') && (i >= 0); i--){
        count++;
    }
    return count;
}

错误原因

两个for循环都存在越界访问的风险:

  1. 第二个循环的条件判断顺序错误:先判断s[i] != ' '再判断i >= 0。当i减到-1时,会先访问s[-1],直接触发堆内存越界报错。
  2. 第一个循环同样存在隐患:如果输入字符串全是空格,i会一直递减到-1,此时访问s[i]也会触发越界。

逻辑与运算符&&是短路求值规则,只要第一个条件不成立,第二个条件不会执行。因此调整条件顺序,先判断i >= 0就能避免越界。

修正后的代码

int lengthOfLastWord(char *s){
    int count = 0;
    int len = strlen(s) - 1;
    int templen = len;
    // 跳过末尾空格,先判断i >=0避免越界
    for (int i = len; i >= 0 && s[i] == ' '; i--){
        templen--;
    }
    // 统计最后一个单词长度,同样先确保i合法
    for (int i = templen; i >= 0 && s[i] != ' '; i--){
        count++;
    }
    return count;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 05:13:24