Module 13 · Lesson 13 of 98

Device memory and CUDA error handling

Allocate, initialize, copy, and release CUDA device buffers, then distinguish launch errors from execution errors and locate an out-of-bounds kernel write.

  • Beginner to advanced
  • 8 min read
  • 40 min lab
What you will need

Ubuntu 24.04 with access to a supported NVIDIA GPU and a working CUDA toolkit with nvcc and Compute Sanitizer. Use a CUDA-capable Jetson with a compatible software stack for the board lab, or a CUDA-enabled Ubuntu 24.04 host for the same exercises.

Your place in the module
By the end you can 4 objectives
  • Allocate and release device buffers with checked CUDA runtime calls.
  • Select the correct cudaMemcpy direction and initialize a buffer by byte.
  • Distinguish launch status from execution status using separate checks.
  • Locate an out-of-bounds kernel write with Compute Sanitizer memcheck.
Video coming soonDevice memory and CUDA error handling
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Vector addition and the CUDA runtime
  • cudaSetDevice selects the current CUDA device for the calling host thread.
  • A kernel launch is asynchronous with respect to the host, and cudaDeviceSynchronize waits for preceding work on the current device.
  • Rounding the grid up covers every element, and the bounds check prevents excess threads from accessing the arrays.
01

Allocate, initialize, and copy a device buffer

4 min read

You ended the last lesson with vector addition running on the GPU. Now you manage the memory behind it and catch mistakes, and this lesson answers how to allocate device memory and handle the errors CUDA reports.

An allocation for four integers can succeed, the kernel can launch successfully, and the kernel can still write to a fifth position. The allocation and launch calls have their own conditions for success. The invalid store occurs when the GPU runs the kernel, and an allocation boundary can be smaller than the range the hardware permits a store to reach. NVIDIA documents the difference in its Compute Sanitizer guide.

A cudaMalloc takes the address of a pointer variable and a size in bytes. On success it writes the device pointer into that variable. Keep both the pointer and the element count available while the buffer is live. Use the original pointer with cudaFree after the last operation that needs it. After a successful free, any saved copies of the pointer refer to an expired allocation.

Calculate the byte count from the same element count the kernel uses. For an int buffer, count * sizeof(int) gives the number of bytes. With a count supplied at runtime, validate it before multiplying. An overflowing size calculation can give cudaMalloc a smaller request than intended, and CUDA can successfully allocate that smaller range. The buffer then has less space than the kernel expects. For a copy, check that both endpoints have room for the requested byte count.

cudaMalloc leaves the contents uninitialized. Initialize all bytes your computation will read, either by copying input, filling the buffer, or writing the elements in a kernel. cudaMemset(ptr, value, bytes) repeats the low eight bits of value over the specified range. With an int buffer, a fill value of 0 produces integer zeros. A fill value of 1 produces the byte pattern 0x01 in every byte. To initialize every int to the numeric value 1, copy an array of ones from the host or assign 1 to each element in a kernel.

Read the parameters of cudaMemcpy(dst, src, bytes, kind) in destination-first order. The kind describes the direction from source to destination.

Copy kind Source Destination
cudaMemcpyHostToDevice CPU-side input CUDA device allocation
cudaMemcpyDeviceToHost CUDA device allocation CPU-side output
cudaMemcpyDeviceToDevice CUDA device allocation Another region of device memory

Use host-to-device to provide inputs and device-to-host to inspect results on the CPU. A device-to-device copy can preserve a snapshot in a second device buffer for later use by the GPU. Keep the source and destination ranges disjoint for cudaMemcpy. On Jetson, CPU and GPU share physical DRAM, and these API directions still describe how the pointers are used. In this lesson, pass the pointer returned by cudaMalloc to CUDA operations and kernels, and inspect its contents through a device-to-host copy. See the CUDA Runtime memory API.

CUDA device buffer lifetimeHostDevice bufferDevice snapshotAllocate inputbufferAllocate snapshotCopy host inputCopy device dataCopy result backFree snapshotFree input buffer1. Host → Device bufferAllocate input buffer2. Host → Device snapshotAllocate snapshot3. Host → Device bufferCopy host input4. Device buffer → DevicesnapshotCopy device data5. Device snapshot → HostCopy result back6. Host → Device snapshotFree snapshot7. Host → Device bufferFree input buffer
The direction of each copy follows the source and destination. Free each device allocation after its final use.
02

Check runtime calls and kernel completion

4 min read

Every operation call shown here, including cudaMalloc, cudaMemcpy, cudaMemset, cudaFree, and cudaDeviceSynchronize, returns a cudaError_t. Compare that return value with cudaSuccess. cudaGetLastError and cudaPeekAtLastError also return cudaError_t. The diagnostic helper cudaGetErrorString takes a status and returns a string. A kernel launch expression has no cudaError_t return value, so it needs a separate check.

The CUDA_CHECK macro records the expression, source file, line number, and error text before terminating the program. Save it at the top of device_memory.cu. These snippets use CUDA C++ and compile with nvcc.

cpp
#include <cuda_runtime.h>
#include <cstddef>
#include <cstdio>
#include <cstdlib>

#define CUDA_CHECK(call)                                                   \
    do {                                                                   \
        const cudaError_t status = (call);                                 \
        if (status != cudaSuccess) {                                       \
            std::fprintf(stderr, "%s:%d: %s: %s\n",                        \
                         __FILE__, __LINE__, #call,                        \
                         cudaGetErrorString(status));                       \
            std::abort();                                                  \
        }                                                                  \
    } while (0)

The macro evaluates call once. The do block makes each invocation behave as a single statement, including when it appears under an if. The diagnostic identifies the host call that reported the error. For an asynchronous execution failure, the actual fault may have occurred at an earlier kernel instruction. std::fprintf writes the diagnostic to standard error and std::abort terminates the process. Use this policy for a small standalone program where execution should stop at the first CUDA failure. A recoverable caller needs an error path that releases resources it already acquired and gives the caller the failure status.

Append this example to the same file. The fill establishes the initial value for every element, the kernel changes one element, and the device-to-device copy preserves the resulting buffer for readback.

cpp
__global__ void store(int *data, int index)
{
    data[index] = 7;
}

int main()
{
    int host[4] = {};
    constexpr std::size_t bytes = sizeof host;
    int *device = nullptr;
    int *snapshot = nullptr;

    CUDA_CHECK(cudaMalloc(&device, bytes));
    CUDA_CHECK(cudaMalloc(&snapshot, bytes));
    CUDA_CHECK(cudaMemset(device, 0, bytes));

    store<<<1, 1>>>(device, 3);
    CUDA_CHECK(cudaGetLastError());
    CUDA_CHECK(cudaDeviceSynchronize());

    CUDA_CHECK(cudaMemcpy(snapshot, device, bytes, cudaMemcpyDeviceToDevice));
    CUDA_CHECK(cudaMemcpy(host, snapshot, bytes, cudaMemcpyDeviceToHost));

    CUDA_CHECK(cudaFree(snapshot));
    CUDA_CHECK(cudaFree(device));

    if (host[0] != 0 || host[1] != 0 || host[2] != 0 || host[3] != 7) {
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
bash
nvcc -lineinfo -o device_memory device_memory.cu
./device_memory

The program verifies the four integers and returns EXIT_SUCCESS on a match. A result mismatch returns EXIT_FAILURE. Each CUDA operation has an independent check, including cleanup, so an error during cleanup also prevents a successful exit. The -lineinfo option emits device line information for diagnostics in the last section.

A kernel launch is normally asynchronous with respect to the host. The CPU can continue while the GPU is still executing the kernel. Immediately after launching, check cudaGetLastError(). A launch with an invalid configuration, such as a block dimension of zero, can be rejected before any GPU instructions run. The returned success code says the runtime has no error to report through that check at that point. Checking cudaDeviceSynchronize() next waits for preceding work on the current device and can report an execution error, such as an illegal memory access. In a program with several outstanding operations, the call that reports the error may have little apparent connection to its cause. In this example the explicit wait narrows the source to the work submitted around a single kernel.

cudaGetLastError() reads and resets the runtime's last-error slot for the calling host thread to cudaSuccess. cudaPeekAtLastError() reads the slot without clearing it. A peek is useful when an observer wants to log an error that another check on the same thread will consume. Both calls may report errors from previous asynchronous work. Neither waits for GPU work, and clearing the slot does not repair a device execution failure. Keep ordinary calls checked and place the launch check immediately after the launch so that you have fewer possible sources to investigate. See the CUDA Runtime error handling API.

Host checks after a kernel launchLaunchkernelChecklaunchstatuscudaGetLastErrorWait andcheckcudaDeviceSynchronizeRead resultExit from step 3: CUDA errorReport and abortLaunchkernelChecklaunchstatuscudaGetLastErrorWait andcheckcudaDeviceSynchronizeRead resultExit from step 3: CUDA errorReport and abort
Check launch status immediately, then check execution status at an explicit synchronization point.
03

Locate a fault inside the kernel

2 min read
Going deeperExplore the mechanism

To see what the two error checks can establish, change the launch argument from 3 to 4 in a separate copy of the example. With four elements, legal indices run from 0 through 3. Index 4 starts immediately after the allocation. The grid and block dimensions are still valid. The launch check can therefore return cudaSuccess, and even synchronization can succeed if the invalid store reaches a hardware-accessible address. In that case the host result check can still fail because the intended element at index 3 remains zero. A program exit status alone cannot distinguish that mismatch from a CUDA error. Record the status from each check and the result of the host comparison separately. If a check aborts, record that the later stages were skipped.

For the diagnostic run, save the modified source as device_memory_oob.cu and use:

bash
nvcc -lineinfo -o device_memory_oob device_memory_oob.cu
compute-sanitizer --tool memcheck --padding 32 ./device_memory_oob

Compute Sanitizer's memcheck tracks device allocation bounds and can identify an invalid global write even when ordinary CUDA execution completes without an illegal-address error. Here --padding 32 adds a 32-byte padding region after supported allocations so that a small overflow cannot be mistaken for a write into an adjacent allocation. Inspect the access type, the named kernel, and the source location if available. The invalid instruction is the store in store. The runtime check, if it fires, identifies the host call that received the failure. Use both locations when diagnosing a larger program: the host location identifies which work was under observation and the device location identifies where to examine the indexing expression.

To observe a guaranteed launch-time failure independently of the out-of-bounds write, use a fresh run with store<<<1, 0>>>(device, 3). The zero block dimension is invalid, so the immediate cudaGetLastError() check detects the launch failure. Restore store<<<1, 1>>>(device, 3) and repeat memcheck. The expected result is a clean memory check and a passing host comparison. The separate launch failure provides a way to verify the launch check even on a system where the one-past-end store produces no runtime error.

Compute Sanitizer also provides --tool racecheck. It detects hazards in shared-memory accesses, for example when one thread reads a shared location while another writes it without the required synchronization. Select memcheck for an invalid address and racecheck for suspected shared-memory access hazards. A clean racecheck run does not establish that global memory accesses are in bounds or that global memory is free of races.

Evidence from a faulty kernelLast errorDevice synchronizationMemcheckEvidenceLaunch statusExecutionstatusInvaliddevice accessLocationHost launchcheckHost waitcallDeviceinstructionOne-past-endstoreCan returnsuccessMay reportfailureTracksallocationbounds
A launch check, a synchronization check, and memcheck report different evidence about a faulty run.

The next lesson, One thread per pixel: grayscale and brightness, uses these same allocation, copy, and error checks around a kernel that processes image data.

Key takeaways

  • CUDA allocation, copy, and fill sizes are expressed in bytes.
  • cudaMemset repeats a byte value across the requested range.
  • cudaGetLastError clears the calling host thread's last-error slot and cudaPeekAtLastError leaves it intact.
  • A successful launch check can precede an execution error reported at synchronization.
Reflect
  1. Explain to a colleague, in two sentences: allocate and release device buffers with checked CUDA runtime calls.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close