
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.
Allocate, initialize, and copy a device buffer
4 min readYou 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 A device allocation is a range of bytes reserved by the CUDA runtime for use by device code. 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.
Check runtime calls and kernel completion
4 min readEvery 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.
#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.
__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;
}
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.
Locate a fault inside the kernel
2 min readGoing 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:
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.
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
- Explain to a colleague, in two sentences: allocate and release device buffers with checked CUDA runtime calls.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- 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.