Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions BadArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
public class BadArray {
private static int[] store = new int[4];

public static void putData(int pos, int num) {
if (pos < 0) {
return;
}
store[pos] = num;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 AI 代码审查发现问题

📋 问题概述

数组越界访问风险
line 5-7 仅校验了 pos < 0 的下限,但未校验 pos >= store.length 的上限。当调用者传入 pos >= 4 时(如 line 12 的 putData(5, 100)),line 8 会触发 ArrayIndexOutOfBoundsException。

📍 问题详情

🔴 问题 1 | 严重程度: HIGH | 行号: 8

💬 详细说明:

  • 任何调用 putData 且传入非法索引的代码都会导致运行时异常崩溃。虽然 Java 有边界检查不会造成内存破坏,但会导致服务不可用或数据丢失。

📝 问题代码:

        store[pos] = num;

💡 修复建议:

在 line 5 的条件中增加上限检查,确保 pos 在 [0, store.length) 范围内。

✅ 修复示例:

    public static void putData(int pos, int num) {
        if (pos < 0 || pos >= store.length) {
            return;
        }
        store[pos] = num;
    }

🔗 参考链接

}

public static void main(String[] args) {
putData(5, 100);
}
}