python/cpython · error

could not allocate %ld bytes

Error message

could not allocate %ld bytes

What it means

Build-time error from Programs/_freeze_module.c: malloc() for a buffer of st_size+1 bytes failed, so the module source cannot be read into memory for compilation. It means the process was out of memory (or hit an allocation limit) at freeze time.

Source

Thrown at Programs/_freeze_module.c:104

read_text(const char *inpath)
{
    FILE *infile = fopen(inpath, "rb");
    if (infile == NULL) {
        fprintf(stderr, "cannot open '%s' for reading\n", inpath);
        return NULL;
    }

    struct _Py_stat_struct stat;
    if (_Py_fstat_noraise(fileno(infile), &stat)) {
        fprintf(stderr, "cannot fstat '%s'\n", inpath);
        fclose(infile);
        return NULL;
    }
    size_t text_size = (size_t)stat.st_size;

    char *text = (char *) malloc(text_size + 1);
    if (text == NULL) {
        fprintf(stderr, "could not allocate %ld bytes\n", (long) text_size);
        fclose(infile);
        return NULL;
    }
    size_t n = fread(text, 1, text_size, infile);
    fclose(infile);

    if (n < text_size) {
        fprintf(stderr, "read too short: got %ld instead of %ld bytes\n",
                (long) n, (long) text_size);
        free(text);
        return NULL;
    }

    text[text_size] = '\0';
    return (const char *)text;
}

static PyObject *

View on GitHub (pinned to bc6749cc3b)

Solutions

  1. Free memory or raise limits: increase container memory, check `ulimit -v`, close other jobs before rebuilding
  2. Verify the inpath is the intended .py file and not something huge: `ls -l <inpath>`
  3. Reduce parallelism (`make -j1`) during the freeze stage to lower peak memory
  4. Add swap on small VMs
Defensive patterns

Strategy: validation

Validate before calling

# shell: sanity-check input size before freezing
# size=$(stat -c %s "$IN" 2>/dev/null || stat -f %z "$IN")
# [ "$size" -lt 10000000 ] || { echo "$IN suspiciously large"; exit 1; }

Prevention

When it happens

Trigger: Freezing a path that is actually enormous (accidentally pointing at a huge file or device), or building in a memory-constrained container/ci runner where malloc of even modest sizes fails.

Common situations: Low-memory CI containers (cgroup limits) building CPython; swap-less small VMs; an outpath/inpath mix-up pointing at a multi-GB file; ulimit -v set restrictively.

Related errors


AI-assisted analysis of python/cpython@bc6749cc3b (2026-08-14). Data as JSON: /api/errors/95782f5aa1b9bdf6. Report an issue: GitHub.