Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

CUDA error handling

Practical notes on detecting and reporting CUDA runtime and kernel errors: what errors mean, how and when they are signalled, and reliable code patterns to check them.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

GPU programs run partly on the CPU (host) and partly on the GPU (device). Bugs, resource limits or incorrect assumptions cause failures that are different from CPU programs. Correct error handling lets an engineer find the real cause quickly and prevents wrong results or crashes in production.

Key ideas

  • Host: the CPU and its memory; the code that calls CUDA functions runs here.
  • Device: the GPU and its memory where kernels run.
  • Kernel: a function written for the device and launched from the host to run many threads in parallel.
  • cudaError_t: the C type returned by most CUDA runtime API calls. It encodes an error code value; cudaSuccess means no error.
  • Asynchronous operation: an operation where the host call returns before the GPU work is finished (example: kernel launches are asynchronous to the host). The CPU and GPU run concurrently until synchronisation is requested.
  • Synchronous operation: an operation that completes before the host call returns (example: cudaMemcpy is synchronous and blocks the host until the transfer completes). For asynchronous copies use cudaMemcpyAsync with a stream; true host asynchrony for H2D/D2H transfers requires pinned (page-locked) host memory.

Exact rules and recommended checks (these are the statements you should memorise):

  1. Every CUDA runtime API call that returns cudaError_t must be checked by the host code if you want reliable error handling. Example: cudaMalloc, cudaMemcpy, cudaFree.
  2. A kernel launch itself does not return a cudaError_t. Instead, the runtime records errors and you must call cudaGetLastError() (or cudaPeekAtLastError()) after the launch to retrieve the launch-time error that happened synchronously at enqueue time. To detect errors that occur during kernel execution, call cudaDeviceSynchronize() and then check the return value: cudaDeviceSynchronize() returns an error if the kernel failed during execution.
  3. Use cudaGetErrorString(cudaError_t) to get a human-readable message for an error code.
  4. For most development flows, use a small helper macro that checks return values, prints file and line, the error string and optionally aborts. This pattern prevents silent failures.

Describe the diagram to draw for an exam: draw a left box labelled "Host (CPU)" and a right box labelled "Device (GPU)". Between them draw arrows labelled with examples: "cudaMemcpy (synchronous)" and "kernel<<<...>>> (asynchronous enqueue)". Optionally add "cudaMemcpyAsync (asynchronous in a stream; requires pinned host memory for overlap)". Under the kernel arrow draw a note: "Check with cudaGetLastError() immediately after launch for launch errors; check with cudaDeviceSynchronize() for runtime/errors during execution." Label a small box around the host showing a macro checkCuda(call) that inspects return values and prints file:line.

Formulas

(For this programming topic, these are the syntax lines to remember.)

cudaError_t status = cudaMalloc(void** devPtr, size_t size); — returns status (type cudaError_t). Use when allocating device memory.

status = cudaMemcpy(void* dst, const void* src, size_t count, cudaMemcpyKind kind); — copy memory between host and device. kind is e.g., cudaMemcpyHostToDevice.

cudaError_t err = cudaGetLastError(); — returns and clears the last recorded runtime error (including kernel launch enqueue-time errors). Used immediately after a kernel launch to detect launch errors.

cudaError_t err = cudaPeekAtLastError(); — returns the last recorded runtime error but does NOT clear it.

cudaError_t err = cudaDeviceSynchronize(); — block host until all preceding device work is done; returns an error if any device work failed during execution.

const char* msg = cudaGetErrorString(cudaError_t err); — returns a human-readable string for err.

if (status != cudaSuccess) { fprintf(stderr, "Error: %s\n", cudaGetErrorString(status)); exit(EXIT_FAILURE); } — canonical check pattern; include file/line for better diagnostics.

Worked examples

Example 1 — correct vector addition with robust error checking (complete program).

// vector_add_check.cu
#include <cstdio>
#include <cstdlib>
#include <cuda_runtime.h>

#define checkCuda(call) do { \
    cudaError_t e = (call); \
    if (e != cudaSuccess) { \
        fprintf(stderr, "%s:%d: CUDA error %d: %s\n", __FILE__, __LINE__, (int)e, cudaGetErrorString(e)); \
        exit(EXIT_FAILURE); \
    } \
} while(0)

__global__ void vecAdd(const float* a, const float* b, float* c, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) c[i] = a[i] + b[i];
}

int main() {
    const int N = 1<<20; // 1,048,576
    size_t bytes = N * sizeof(float);

    float *h_a = (float*)malloc(bytes);
    float *h_b = (float*)malloc(bytes);
    float *h_c = (float*)malloc(bytes);
    for (int i = 0; i < N; ++i) { h_a[i] = i * 1.0f; h_b[i] = 2.0f; }

    float *d_a, *d_b, *d_c;
    checkCuda(cudaMalloc((void**)&d_a, bytes));
    checkCuda(cudaMalloc((void**)&d_b, bytes));
    checkCuda(cudaMalloc((void**)&d_c, bytes));

    checkCuda(cudaMemcpy(d_a, h_a, bytes, cudaMemcpyHostToDevice));
    checkCuda(cudaMemcpy(d_b, h_b, bytes, cudaMemcpyHostToDevice));

    int block = 256;
    int grid = (N + block - 1) / block;
    vecAdd<<<grid, block>>>(d_a, d_b, d_c, N);

    // Check for launch-time error
    checkCuda(cudaGetLastError());
    // Check for execution errors (on device)
    checkCuda(cudaDeviceSynchronize());

    checkCuda(cudaMemcpy(h_c, d_c, bytes, cudaMemcpyDeviceToHost));

    // Print first 5 results
    printf("First 5 results:\n");
    for (int i = 0; i < 5; ++i) printf("%d: %f\n", i, h_c[i]);

    cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
    free(h_a); free(h_b); free(h_c);
    printf("Done\n");
    return 0;
}

Sample output (exact):

First 5 results: 0: 2.000000 1: 3.000000 2: 4.000000 3: 5.000000 4: 6.000000 Done

Example 2 — show a runtime API error and how the macro reports it. This program intentionally calls cudaMemcpy with a NULL device pointer to produce a detected error.

// error_example.cu
#include <cstdio>
#include <cstdlib>
#include <cuda_runtime.h>

#define checkCuda(call) do { \
    cudaError_t e = (call); \
    if (e != cudaSuccess) { \
        fprintf(stderr, "%s:%d: CUDA error %d: %s\n", __FILE__, __LINE__, (int)e, cudaGetErrorString(e)); \
        /* do not exit to show program flow if you want */ exit(EXIT_FAILURE); \
    } \
} while(0)

int main() {
    int N = 1024;
    size_t bytes = N * sizeof(float);
    float* h = (float*)malloc(bytes);
    for (int i = 0; i < N; ++i) h[i] = 1.0f;

    float* d = NULL; // intentionally not allocated
    // This will fail and return an error because d is NULL
    cudaError_t err = cudaMemcpy(d, h, bytes, cudaMemcpyHostToDevice);
    if (err != cudaSuccess) {
        fprintf(stderr, "Expected error: %s\n", cudaGetErrorString(err));
    } else {
        printf("Unexpected success\n");
    }

    // Show checkCuda macro would have exited with message and location
    // checkCuda(cudaMemcpy(d, h, bytes, cudaMemcpyHostToDevice));

    free(h);
    return 0;
}

Sample output (exact; exact message string depends on installed CUDA but typical):

Expected error: invalid argument

(If you uncomment the checkCuda call, the program exits and prints file:line with the same message.)

Common mistakes

  • Ignoring errors reported from other streams. If you use streams, errors may be reported when you synchronise that stream with cudaStreamSynchronize(stream) or call cudaDeviceSynchronize(), and some blocking runtime API calls (e.g., cudaMemcpy) may also surface prior asynchronous errors.
  • Relying on kernel printf output without synchronisation; the host may exit before device printf flushes.
  • Not printing file and line number when checking errors; this makes debugging slower.

For your exam

Kinds of questions you will see:

  • Definitions: define terms like cudaError_t, asynchronous, cudaGetLastError, cudaDeviceSynchronize. Give the exact behavior difference between cudaGetLastError() and cudaDeviceSynchronize().
  • Short notes: explain how to check errors for kernel launches and for runtime API calls; show a macro for error checking.
  • Derivation/diagram: draw the host-device interaction diagram and label where errors can be detected and how (immediately after launch vs after sync).
  • Programs: write a short CUDA program that demonstrates checking a return value and checking kernel launch errors.

Full-marks answers include:

  • Clear definitions with the difference between host/device, synchronous/asynchronous.
  • A correct pattern showing checks after API calls and after kernel launches, including cudaGetLastError() and cudaDeviceSynchronize().
  • Explanation of why both are needed and an example macro.

Quick check

  1. Which CUDA function returns and clears the last recorded runtime error?
  2. After a kernel launch, which call tells you whether the kernel failed during execution?
  3. True/False: cudaMalloc returns void and throws exceptions on error.

Answers: cudaGetLastError(); cudaDeviceSynchronize(); False (cudaMalloc returns cudaError_t you must check).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?