Evitar índices fuera de rango
La comprobación de límites if (i < n).
Evitar índices fuera de rango es una lección gratuita de CUDA Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de CUDA Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de CUDA Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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. 🛡️
Preguntas frecuentes
¿La lección «Evitar índices fuera de rango» es gratis?
Sí — el texto completo de «Evitar índices fuera de rango» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de CUDA Academy, actualiza a CoddyKit PRO. El curso de CUDA Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Evitar índices fuera de rango»?
La comprobación de límites if (i < n). Practicas CUDA Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar CUDA Academy?
No se requiere experiencia previa. CUDA Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «Evitar índices fuera de rango»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de CUDA Academy?
Sí. Cada lección de CUDA Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- La fórmula clásica de indexación
- Evitar índices fuera de rango
- Redondear hacia arriba el número de bloques
- Bucles con salto de cuadrícula