cudaMalloc

Allocate memory on the GPU

Syntax

cpp
1
cudaError_t cudaMalloc(void **devPtr, size_t size);

Parameters

devPtr
Address of your pointer variable (&d). On success it receives the device address.
size
Number of bytes, not elements: n * sizeof(float). A size of 0 succeeds and sets the pointer to NULL.

Returns

cudaSuccess
The memory was allocated.
cudaErrorMemoryAllocation
Not enough free GPU memory ("out of memory"). The pointer is not valid.
cudaErrorInvalidValue
An invalid argument, such as a null devPtr.
errors from earlier launches
Like most runtime calls, it can also return an error left by an earlier asynchronous kernel, such as cudaErrorIllegalAddress.

How it works

Why it takes void**

The function needs to give you two things: an error code and an address. The error code is the return value, so the address is written through the pointer you pass in. cudaMalloc(&d, bytes) changes your d; passing d itself would only change a copy.

The memory starts uninitialised

It holds whatever was there before. Use cudaMemset(d, 0, bytes) or copy data in with cudaMemcpy before reading it.

Allocate once, reuse often

Allocation is slow compared with a kernel launch. Allocate buffers before your main loop and reuse them, or use cudaMallocAsync with a memory pool when sizes change every iteration.

Related allocators

cudaMallocManaged returns memory both the CPU and GPU can read. cudaMallocHost returns pinned host memory for faster copies; free it with cudaFreeHost, not cudaFree.

Example

Press Run to execute this on a real NVIDIA GPU in the playground.

Example
main.cu
12345678910111213141516171819202122232425262728293031323334353637
#include <cstdio>
#include <cstdlib>
#include <cuda_runtime.h>

#define CUDA_CHECK(call)                                                  \
    do {                                                                  \
        cudaError_t err_ = (call);                                        \
        if (err_ != cudaSuccess) {                                        \
            fprintf(stderr, "%s:%d: %s (%s)\n", __FILE__, __LINE__,       \
                    cudaGetErrorString(err_), cudaGetErrorName(err_));    \
            exit(1);                                                      \
        }                                                                 \
    } while (0)

__global__ void iota(int *x, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) x[i] = i;
}

int main() {
    const int n = 1000;
    const size_t bytes = n * sizeof(int);

    int *d = nullptr;
    CUDA_CHECK(cudaMalloc(&d, bytes));        // pass the address of the pointer
    printf("256-byte aligned: %s\n", (size_t)d % 256 == 0 ? "yes" : "no");

    iota<<<(n + 255) / 256, 256>>>(d, n);
    CUDA_CHECK(cudaGetLastError());

    int last;
    CUDA_CHECK(cudaMemcpy(&last, d + n - 1, sizeof(int), cudaMemcpyDeviceToHost));
    printf("x[%d] = %d\n", n - 1, last);

    CUDA_CHECK(cudaFree(d));
    return 0;
}
Output on an NVIDIA T4
256-byte aligned: yes
x[999] = 999

Common mistakes

Passing the pointer instead of its address

cudaMalloc((void **)d, bytes) compiles because of the cast, but writes the address into random memory. Write cudaMalloc(&d, bytes); recent CUDA versions accept a typed pointer without a cast.

Elements instead of bytes

cudaMalloc(&d, n) for an int array allocates a quarter of what you need, and the kernel then writes past the end. Always multiply by sizeof.

Reading device memory on the CPU

printf("%d", d[0]) on the host crashes with a segmentation fault. Copy the value back with cudaMemcpy first.

Not checking the result

When the GPU is full, the pointer is left invalid and the first kernel that uses it fails with an illegal memory access, far from the real cause.

FAQ

What is the difference between cudaMalloc and malloc?

malloc returns CPU memory that only host code can use. cudaMalloc returns GPU memory that only device code can use directly. Data moves between them with cudaMemcpy.

How much memory can I allocate with cudaMalloc?

Up to what is currently free on the GPU, which cudaMemGetInfo reports. On a shared GPU, other processes and per-process limits can leave less than that, so check the return value instead of assuming a large allocation will succeed.