Back to Blog
critical SEVERITY8 min read

Heap Buffer Overflow in darktable's Color Chart: How Unchecked memcpy Calls Put Image Processing at Risk

A critical heap buffer overflow vulnerability was discovered in `src/chart/main.c`, where `memcpy` and `memmove` calls failed to validate buffer sizes before copying color calibration data — allowing a crafted input file to overwrite heap metadata and adjacent memory. The fix adds allocation failure checks after `realloc` calls and replaces `malloc` with `calloc` to zero-initialize buffers, eliminating the risk of uninitialized memory being exploited. This type of vulnerability is a reminder tha

O
By Orbis AppSec
Published May 28, 2026Reviewed June 3, 2026

Answer Summary

This is a heap buffer overflow vulnerability (CWE-122) in C code where `memcpy` and `memmove` calls in darktable's `src/chart/main.c` failed to validate buffer sizes before copying color calibration data. The fix adds allocation failure checks after `realloc` calls and replaces `malloc` with `calloc` to zero-initialize buffers, preventing both heap corruption and uninitialized memory exploitation.

Vulnerability at a Glance

cweCWE-122
fixAdded allocation failure checks and replaced malloc with calloc for zero-initialization
riskArbitrary code execution via crafted color chart input files
languageC
root causeMissing buffer size validation before memcpy/memmove operations
vulnerabilityHeap Buffer Overflow

Heap Buffer Overflow in Color Chart Processing: How Unchecked memcpy Calls Put Image Processing at Risk

Introduction

Memory safety bugs are among the oldest and most dangerous classes of vulnerabilities in software. Despite decades of awareness, buffer overflows — particularly heap-based ones — continue to appear in production codebases, even in well-maintained open-source projects. This post examines a critical heap buffer overflow (CWE-120) discovered and fixed in a color chart calibration tool written in C, walking through exactly how the bug works, how it could be exploited, and what the fix looks like.

Whether you're a C developer, a security researcher, or a developer working in higher-level languages who wants to understand what happens "under the hood," this post will give you a clear, practical understanding of heap buffer overflows and how to prevent them.


The Vulnerability Explained

What Is a Heap Buffer Overflow?

A heap buffer overflow occurs when a program writes more data into a heap-allocated buffer than the buffer can hold. Unlike stack overflows, which are often caught by modern stack canaries and OS protections, heap overflows can be subtler and harder to detect — and they can be devastatingly effective for attackers who know how to manipulate heap metadata.

In this case, the vulnerable code lives in src/chart/main.c, inside a function called add_hdr_patches. This function is responsible for dynamically expanding several arrays (target_L, target_a, target_b, and colorchecker_Lab) to accommodate extra color patches read from a calibration file.

The Vulnerable Code

Here's the core of the problem, before the fix:

*target_L = realloc(*target_L, sizeof(double) * (*N + n_extra_patches + 4));
*target_a = realloc(*target_a, sizeof(double) * (*N + n_extra_patches + 4));
*target_b = realloc(*target_b, sizeof(double) * (*N + n_extra_patches + 4));
*colorchecker_Lab = realloc(*colorchecker_Lab, sizeof(double) * 3 * (*N + n_extra_patches));

memmove(&(*target_L)[n_extra_patches], *target_L, sizeof(double) * *N);
memmove(&(*target_a)[n_extra_patches], *target_a, sizeof(double) * *N);
memmove(&(*target_b)[n_extra_patches], *target_b, sizeof(double) * *N);

There are two distinct problems here:

Problem 1: No Check for realloc Failure

In C, realloc can fail. When it does, it returns NULL — and the original pointer is not freed, but it is also no longer accessible through the variable (since it's been overwritten with NULL). If the code proceeds to call memmove on a NULL pointer, the result is undefined behavior, typically a segmentation fault or, worse, a silent memory corruption.

Problem 2: No Validation of n_extra_patches

The value of n_extra_patches is derived from a user-supplied calibration file. If an attacker crafts a file with an extremely large n_extra_patches value, two things can go wrong:

  1. The realloc call may fail silently (see above).
  2. Even if realloc succeeds, the subsequent memmove with sizeof(double) * *N bytes into an offset of n_extra_patches could write beyond the end of the allocated buffer if the arithmetic overflows or if the sizes weren't computed consistently.

How Could This Be Exploited?

Consider an attacker who can supply a crafted .cht (color chart) or calibration file to the application. By encoding a large n_extra_patches value:

  1. The realloc calls attempt to allocate a massive buffer.
  2. On systems with limited memory, realloc may return NULL.
  3. The memmove is then called with a NULL destination pointer — writing data to address NULL + offset, which on some platforms and configurations can be a valid (if dangerous) memory location.
  4. Alternatively, even with a successful allocation, carefully chosen values can cause the memmove to write past the end of the buffer, corrupting heap metadata or adjacent heap objects.

Heap metadata corruption is particularly dangerous because it can be leveraged to redirect program execution — a technique well-documented in heap exploitation research. In a worst-case scenario, this could allow arbitrary code execution on the machine processing the calibration file.

Real-World Impact

  • Arbitrary code execution via crafted color chart files
  • Denial of service through application crash
  • Memory corruption leading to unpredictable program behavior
  • Any user or automated pipeline that processes untrusted calibration files is at risk

The Fix

The fix addresses both root causes cleanly and follows established C security best practices.

Fix 1: Validate realloc Return Values

// BEFORE: No check after realloc
*target_L = realloc(*target_L, sizeof(double) * (*N + n_extra_patches + 4));
*target_a = realloc(*target_a, sizeof(double) * (*N + n_extra_patches + 4));
*target_b = realloc(*target_b, sizeof(double) * (*N + n_extra_patches + 4));
*colorchecker_Lab = realloc(*colorchecker_Lab, sizeof(double) * 3 * (*N + n_extra_patches));

// Immediately proceeds to memmove — dangerous!
memmove(&(*target_L)[n_extra_patches], *target_L, sizeof(double) * *N);
// AFTER: Allocation failure is detected and handled
*target_L = realloc(*target_L, sizeof(double) * (*N + n_extra_patches + 4));
*target_a = realloc(*target_a, sizeof(double) * (*N + n_extra_patches + 4));
*target_b = realloc(*target_b, sizeof(double) * (*N + n_extra_patches + 4));
*colorchecker_Lab = realloc(*colorchecker_Lab, sizeof(double) * 3 * (*N + n_extra_patches));

if(!*target_L || !*target_a || !*target_b || !*colorchecker_Lab)
{
  fprintf(stderr, "error: failed to allocate memory for extra patches\n");
  exit(EXIT_FAILURE);
}

// Only proceeds to memmove if all allocations succeeded
memmove(&(*target_L)[n_extra_patches], *target_L, sizeof(double) * *N);

This guard ensures that if any allocation fails, the program exits cleanly rather than proceeding with a NULL pointer. While exit(EXIT_FAILURE) is a blunt instrument (a more robust application might propagate an error code up the call stack), it is vastly preferable to undefined behavior or exploitable memory corruption.

Fix 2: Replace malloc with calloc for Zero-Initialization

In the process_data function, several buffers were allocated with malloc:

// BEFORE: malloc leaves memory uninitialized
double *cx = malloc(sizeof(double)*N);
double *cy = malloc(sizeof(double)*N);
double *grays = malloc(sizeof(double) * 6 * N);
// AFTER: calloc zero-initializes memory
double *cx = calloc(N, sizeof(double));
double *cy = calloc(N, sizeof(double));
double *grays = calloc(N, 6 * sizeof(double));

This change has two security benefits:

  1. Zero-initialization ensures that uninitialized memory cannot contain sensitive data from a previous allocation (information leakage).
  2. Predictable initial state reduces the risk of logic bugs caused by reading uninitialized values — a class of bugs that can sometimes be exploited to influence program behavior.

Note also that calloc(N, sizeof(double)) is safer against integer overflow than malloc(N * sizeof(double)) — on some platforms, calloc implementations check for multiplication overflow internally.

The Same Fix Applied to RGB Tonecurve Buffers

The same malloccalloc change was applied to the RGB tonecurve buffer allocations:

// BEFORE
cx = malloc(sizeof(double)*num_tonecurve);
cy = malloc(sizeof(double)*num_tonecurve);

// AFTER
cx = calloc(num_tonecurve, sizeof(double));
cy = calloc(num_tonecurve, sizeof(double));

This is a defense-in-depth improvement: even if the immediate code paths don't trigger exploitable uninitialized reads, zero-initializing buffers removes an entire category of potential future bugs.


Conclusion

This vulnerability is a textbook example of how a missing null check and unvalidated input can turn routine memory operations into a critical security risk. The add_hdr_patches function was doing exactly what it was supposed to do — dynamically resize arrays for color data — but without the defensive checks that C programming demands.

The fix is elegant in its simplicity: check your allocations, zero-initialize your buffers, and never trust input-derived sizes without validation. These are not exotic techniques; they are foundational C programming hygiene that every developer working in systems languages should internalize.

Key takeaways:

  • Always check realloc/malloc return values before using the pointer
  • Prefer calloc over malloc for array allocations to get zero-initialization and overflow-safe size computation
  • Validate input-derived sizes before using them in memory operations
  • Use sanitizers and static analysis as part of your CI/CD pipeline to catch these issues early
  • Treat file parsing code as an attack surface — any file format that accepts numeric values can be a vector for this type of attack

Memory safety is not just a performance concern — it's a security concern. In a world where automated tools can fuzz applications with millions of crafted inputs per second, the cost of a missing null check can be measured in compromised systems.


This vulnerability was identified and fixed as part of an automated security scanning and remediation workflow. Automated security tooling can catch issues like this at scale — but understanding why they're dangerous is what turns a patch into lasting secure coding knowledge.

Prevention and further reading

View the Security Fix

Check out the pull request that fixed this vulnerability

View PR #20996

Related Articles

critical

How buffer overflow happens in C++ and how to fix it

A critical buffer overflow in `create_hex_string()` within `hmlangw.cpp` let an unconditional 16-iteration loop write past the bounds of a 100-byte `hex` buffer using unchecked `sprintf` calls. The fix replaces `sprintf` with `snprintf` and caps the loop iterations based on the actual destination buffer size, closing off a memory corruption path reachable from serial or network input.

critical

How Buffer Overflow via strcpy() Happens in C++ XML Parsers and How to Fix It

A critical buffer overflow vulnerability was discovered in `buildroot-external/package/libxmlparser/xmlParser.cpp`, where the `toXMLString` function used `_tcscpy()` to write XML escape sequences into a destination buffer without any bounds checking. An attacker supplying a crafted XML document could overflow the buffer and potentially execute arbitrary code. The fix replaces all five unsafe `_tcscpy()` calls with `memcpy()` calls that copy only the exact number of bytes required for each escape

critical

How Heap Buffer Overflows Happen in C++ ZIP Extraction and How to Fix Them

A critical heap buffer overflow vulnerability was discovered in `TKLiveSync/unzip.cpp`, where ZIP archive entry names were copied into a `PATH_MAX`-sized heap buffer using `strcpy()` without any length validation. Since the ZIP specification allows entry names up to 65,535 bytes — far exceeding typical `PATH_MAX` values of 1,024 to 4,096 bytes — a crafted archive could overflow the buffer and corrupt heap memory. The fix replaces the unsafe `strcpy`/`dirname` pattern with `std::string` operation

medium

How Integer Overflow happens in C++ image processing and how to fix it

A signed integer overflow in OpenCV's `bilateralFilter.cpp` allowed the buffer size calculation `cal_width * cal_height * cn` to wrap around to a small or negative value, causing `padding.resize()` to allocate far less memory than needed. Subsequent `memcpy` operations would then write beyond the allocated buffer, creating a heap corruption primitive. The fix is a single targeted cast to `size_t` that promotes the multiplication to unsigned 64-bit arithmetic before any overflow can occur.

critical

How Stack Buffer Overflows Happen in C with sprintf() and How to Fix Them

A critical stack buffer overflow was discovered in `libuv/Learn-libuv/docs/code/tty-gravity/main.c` where `sprintf()` wrote ANSI escape sequences and user-controlled variables into a fixed 500-byte buffer without any bounds checking. An attacker controlling the `pos`, `width`, or `message` variables could overflow the stack, overwrite return addresses, and potentially achieve arbitrary code execution. The fix replaces `sprintf()` with `snprintf()` and adds explicit length validation to ensure wr

high

How insecure string copy functions happen in C and how to fix them

A high-severity buffer overflow risk was discovered in `login/main.c` where `strcpy()` was used to copy the `HOME` environment variable into a fixed-size 512-byte buffer without any bounds checking. An attacker controlling the `HOME` environment variable could overflow `pwd_file_name`, potentially corrupting memory or hijacking execution. The fix replaces the two-step `strcpy`/`strcat` pattern with a single, bounds-safe `snprintf` call.