防止索引超出范围
使用 if (i < n) 进行边界检查
防止索引超出范围 是 CoddyKit 上的免费 CUDA Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 CUDA Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 CUDA Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
You Often Launch Too Many
Thread counts come in fixed block sizes, so you almost always launch a few extra threads beyond your array length. Those spares need handling.
What Goes Wrong
An extra thread computes an index past the end of the array. If it writes there, it touches memory it does not own, causing a silent out-of-bounds bug.
The GPU Will Not Warn You
Unlike a clean crash, an out-of-range write may corrupt nearby data or read garbage. The kernel keeps running, so the failure is invisible until results look wrong.
The Fix Is One Line
Before any thread uses its index, check that it falls inside the array. This tiny bounds check is the most important safety habit in CUDA.
if (i < n) {
out[i] = a[i] + b[i];
}Why Less Than, Not Less Or Equal
Valid indices run 0 to n minus 1. The strict i < n lets the last real element through and stops the first invalid one.
Idle Threads Just Exit
A thread whose index is out of range simply skips the work and returns. Doing nothing is perfectly safe and costs almost no time.
Pass n to the Kernel
The kernel cannot guess the array length, so you give it n as a parameter. Then the guard always knows where the data ends.
__global__ void add(float* a, float* b, float* out, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) out[i] = a[i] + b[i];
}Guard Reads Too
It is not only writes. Reading a[i] past the end loads garbage or faults, so the same i < n check protects every access.
A Common Off-by-One
Writing i <= n by mistake lets one thread touch element n, which does not exist. Always keep the comparison strict.
Cheap Insurance
The branch costs almost nothing because extra threads are rare and exit fast. The safety it buys is worth far more than that tiny cost. ✅
Make It a Reflex
Treat the bounds check as part of the index formula itself. Compute i, then immediately guard it before doing anything else.
Quick Check
Pick the correct guard.
Recap
You learned to add if (i < n) after computing the index. This one line stops out-of-range reads and writes that the GPU would never warn you about. 🛡️
常见问题解答
「防止索引超出范围」课时是免费的吗?
是的 — 「防止索引超出范围」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 CUDA Academy 课程的其余内容,请升级到 CoddyKit PRO。 CUDA Academy 课程共包含 4 节课。
「防止索引超出范围」这节课中我会学到什么?
使用 if (i < n) 进行边界检查 你通过在浏览器中直接运行的动手代码来练习 CUDA Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 CUDA Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 CUDA Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「防止索引超出范围」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 CUDA Academy 课中编写并运行代码吗?
能。每节 CUDA Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 经典索引公式
- 防止索引超出范围
- 向上取整计算线程块数量
- 网格步长循环