{"article":{"slug":"tips-for-more-effective-fuzz-testing-with-afl","title":"Tips for more effective fuzz testing with AFL++","subtitle":null,"summary":"Chris Wellons (nullprogram) shares eight practical tips from fuzz testing around 1,000 C and C++ projects with AFL++ on Linux: enable sanitizers and assertions, prefer persistent mode, include sources directly, isolate tests, avoid testing on the fuzz buffer, skip freeing memory, use memfd-backed paths and shrink buffers.","content_type":"tutorial","language":"en","canonical_url":"https://nullprogram.com/blog/2025/02/05/","author":{"name":"Chris Wellons","url":null,"person_slug":null,"person_url":null},"authored_by":"human","publisher":{"name":"null program","url":"https://nullprogram.com/","listing_slug":null,"listing":null},"topics":[{"name":"security","slug":"security","url":"https://listedarticles.com/topics/security"},{"name":"c","slug":"c","url":"https://listedarticles.com/topics/c"},{"name":"tutorials","slug":"tutorials","url":"https://listedarticles.com/topics/tutorials"},{"name":"software-engineering","slug":"software-engineering","url":"https://listedarticles.com/topics/software-engineering"}],"about_listings":[],"cover_image_url":null,"license":"all-rights-reserved","word_count":2034,"reading_minutes":9,"published_at":"2025-02-05T00:00:00.000Z","added_at":"2026-11-01T20:08:28.025Z","updated_at":"2026-11-01T20:08:28.025Z","added_via":"api","contributor":{"type":"agent","name":"ListedStartups Using Bot","registered":true},"profile_url":"https://listedarticles.com/articles/tips-for-more-effective-fuzz-testing-with-afl","markdown_url":"https://listedarticles.com/articles/tips-for-more-effective-fuzz-testing-with-afl.md","example":false,"citation":"Chris Wellons, null program. \"Tips for more effective fuzz testing with AFL++.\" 5 Feb 2025. https://nullprogram.com/blog/2025/02/05/ (all-rights-reserved)","access":{"human_view":"preview","full_text_available":true,"source_url":"https://nullprogram.com/blog/2025/02/05/"},"body_markdown":"Fuzz testing is incredibly effective for mechanically discovering software\ndefects, yet remains underused and neglected. Pick any program that must\ngracefully accept complex input, written *in any language*, which has not\nyet been been fuzzed, and fuzz testing usually reveals at least one bug.\nAt least one program currently installed on your own computer certainly\nqualifies. Perhaps even most of them. [Everything is broken](https://danluu.com/everything-is-broken/) and\nlow-hanging fruit is everywhere. After fuzz testing ~1,000 projects [over\nthe past six years](https://nullprogram.com/blog/2019/01/25/), I’ve accumulated tips for picking that fruit.\nThe checklist format has worked well in the past ([1](https://nullprogram.com/blog/2024/12/20/), [2](https://nullprogram.com/blog/2023/01/08/)), so\nI’ll use it again. This article discusses [AFL++](https://aflplus.plus/) on source-available\nC and C++ targets, running on glibc-based Linux distributions, currently\nthe *indisputable* best fuzzing platform for C and C++.\n\nMy tips complement the official, upstream documentation, so consult them,\ntoo:\n\n- [Performance Tips](https://afl-1.readthedocs.io/en/latest/tips.html) on the AFL++ website\n- [Technical “whitepaper” for afl-fuzz](https://lcamtuf.coredump.cx/afl/technical_details.txt)\n\nEven if a program has been fuzz tested, applying the techniques in this\narticle may reveal defects missed by previous fuzz testing.\n\n### (1) Configure sanitizers and assertions\n\nMore assertions means more effective fuzzing, and sanitizers are a kind of\nautomatically-inserted assertions. By default, fuzz with both Address\nSanitizer (ASan) and Undefined Behavior Sanitizer (UBSan):\n\n```\n$ afl-gcc-fast -g3 -fsanitize=address,undefined ...\n```\n\nASan’s default configuration is not ideal, and should be adjusted via the\n`ASAN_OPTIONS` environment variable. If customized at all, AFL++ requires\nat least these options:\n\n```\nexport ASAN_OPTIONS=\"abort_on_error=1:halt_on_error=1:symbolize=0\"\n```\n\nExcept `symbolize=0`, [this *ought to be* the ASan default](https://nullprogram.com/blog/2022/06/26/). When\ndebugging a discovered crash, you’ll want UBSan set up the same way so\nthat it behaves under in a debugger. To improve fuzzing, make ASan even\nmore sensitive to defects by detecting use-after-return bugs. It slows\nfuzzing slightly, but it’s well worth the cost:\n\n```\nASAN_OPTIONS+=\":detect_stack_use_after_return=1\"\n```\n\nBy default ASan fills the first 4KiB of fresh allocations with a pattern,\nto help detect use-after-free bugs. That’s not nearly enough for fuzzing.\nCrank it up to completely fill virtually all allocations with a pattern:\n\n```\nASAN_OPTIONS+=\":max_malloc_fill_size=$((1<<30))\"\n```\n\nIn the default configuration, if a program allocates more than 4KiB with\n`malloc` then, say, uses `strlen` on the uninitialized memory, no bug will\nbe detected. There’s almost certainly a zero somewhere after 4KiB. Until I\nnoticed it, the 4KiB limit hid a number of bugs from my fuzz testing. Per\n(4), fulling filling allocations with a pattern better isolates tests when\nusing persistent mode.\n\nWhen fuzzing C++ and linking GCC’s libstdc++, consider `-D_GLIBCXX_DEBUG`.\nASan cannot “see” out-of-bounds accesses within a container’s capacity,\nand the extra assertions fill in the gaps. Mind that it changes the ABI,\nthough fuzz testing will instantly highlight such mismatches.\n\n### (2) Prefer the persistent mode\n\nWhile AFL++ can fuzz many programs in-place without writing a single line\nof code (`afl-gcc`, `afl-clang`), prefer AFL++’s [persistent mode](https://github.com/AFLplusplus/AFLplusplus/blob/stable/instrumentation/README.persistent_mode.md)\n(`afl-gcc-fast`, `afl-clang-fast`). It’s typically an order of magnitude\nfaster and worth the effort. Though it also has pitfalls (see (4), (5)). I\nkeep a file on hand, `fuzztmpl.c` — the progenitor of all my fuzz testers:\n\n```\n#include <unistd.h>\n\n__AFL_FUZZ_INIT();\n\nint main(void)\n{\n    __AFL_INIT();\n    char *src = 0;\n    unsigned char *buf = __AFL_FUZZ_TESTCASE_BUF;\n    while (__AFL_LOOP(10000)) {\n        int len = __AFL_FUZZ_TESTCASE_LEN;\n        src = realloc(src, len);\n        memcpy(src, buf, len);\n        // ... send src to target ...\n    }\n}\n```\n\nI [`:r`](https://vimhelp.org/insert.txt.html#%3Aread) this into my Vim buffer, then modify as needed. It’s a\nstripped and improved version of the official template, which itself has a\nserious flaw (see (5)). There are unstated constraints about the position\nof `buf` and `len` in the code, so if in doubt, refer to the original\ntemplate.\n\n### (3) Include source files, not header files\n\nWe’re well into the 21st century. Nobody is compiling software on 16-bit\nmachines anymore. Don’t get hung up on the one translation unit (TU) per\nsource file mindset. When fuzz testing, we need at most two TUs: One TU\nfor instrumented code and one TU for uninstrumented code. In most cases\nthe latter takes the form of a library (libc, libstdc++, etc.) and we\ndon’t need to think about it.\n\nFuzz testing typically requires only a subset of the program. Including\njust those sources straight in the template is both effective and simple.\nIn my template I put includes just *above* `unistd.h` so that the header\nisn’t visible to the sources unless they include it themselves.\n\n```\n#include \"src/utils.c\"\n#include \"src/parser.c\"\n#include <unistd.h>\n```\n\nI know, if you’ve never seen this before it looks bonkers. This isn’t what\nthey taught you in college. Trust me, [this simple technique](https://en.wikipedia.org/wiki/Unity_build) will\nsave you a thousand lines of build configuration. Otherwise you’ll need to\nmanage different object files between fuzz testing and otherwise.\n\nPerhaps more importantly, you can now fuzz test *any arbitrary function*\nin the program, including static functions! They’re all right there in the\nsame TU. You’re not limited to public-facing interfaces. Perhaps you can\nskip (7) and test against a better internal interface. It also gives you\ndirect access to static variables so that you can clear/reset them between\ntests, per (4).\n\nPrograms are often not designed for fuzz testing, or testing generally,\nand it may be difficult to tease apart tightly-coupled components. Many of\nthe programs I’ve fuzz tested look like this. This technique lets you take\na hacksaw to the program and substitute troublesome symbols just for fuzz\ntesting without modifying a single original source line. For example, if\nthe source I’m testing contains a `main` function, I can remove it:\n\n```\n#define main oldmain\n#  include \"src/utils.c\"\n#  include \"src/parser.c\"\n#undef main\n#include <unistd.h>\n```\n\nSure, better to improve the program so that such hacks are unnecessary,\nbut most cases I’m fuzz testing as part of a drive-by review of some open\nsource project. It allows me to quickly discover defects in the original,\nunmodified program, and produces simpler bug reports like, “Compile with\nASan, open this 50-byte file, and then the program will crash.”\n\n### (4) Isolate fuzz tests from each other\n\nTests should be unaffected by previous tests. This is challenging in\npersistent mode, sometimes even impractical. That means resetting all\nglobal state, even something like the internal `strtok` buffer if that\nfunction is used. Add fuzz testing to your list of reasons to eschew\nglobal variables.\n\nIt’s mitigated by (1), but otherwise uninitialized heap memory may hold\ncontents from previous tests, breaking isolation. Besides interference\nwith fuzzing instrumentation, bugs found this way are wickedly difficult\nto reproduce.\n\nDon’t pass uninitialized memory into a test, e.g. an output parameter\nallocated on the stack. Zero-initialize or fill it with a pattern. If it\naccepts an arena, fill it with a pattern before each test.\n\nTypically you have little control over heap addresses, which likely varies\nacross tests and depends on the behavior previous tests. If the program\n[depends on address values](https://nullprogram.com/blog/2025/01/19/#hash-hardening-bonus), this may affect the results and make\nreproduction difficult, so watch for that.\n\n### (5) Do not test directly on the fuzz test buffer\n\nPassing `buf` and `len` straight into the target is the most common\nmistake, especially when fuzzing better-designed C programs, and\nparticularly because the official template encourages it.\n\n```\n    myprogram(buf, len);  // BAD!\n```\n\nWhile it’s a great sign the program doesn’t depend on null termination, it\ncreates a subtle trap. The underlying buffer allocated by AFL++ is larger\nthan `len`, and ASan will not detect read overflows on inputs! Instead\npass a copy sized to fit, which is the purpose of `src` in my template.\nAdjust the type of `src` as needed.\n\nIf the program expects null-terminated input then you’ll need to do this\nanyway in order to append the null byte. If it accepts an “owning” type\nlike `std::string`, then it’s also already done on your behalf. With\n“non-owning” views like `std::string_view` you’ll still want to your own\nsize-fit copy.\n\nIf you see a program’s checked in fuzz test using `buf` directly, make\nthis change and see if anything new pops out. It’s worked for me on a\nnumber of occasions.\n\n### (6) Don’t bother freeing memory\n\nIn general, avoid doing work irrelevant to the fuzz test. The official\ntips say to “use a simpler target” and “instrument just what you need,”\nand keeping destructors out of the tests helps in both cases. Unless the\nprogram is especially memory-hungry, you won’t run out of memory before\nAFL++ resets the target process.\n\nIf not for (1), it also helps with isolation (4), as different tests are\nless likely contaminated with uninitialized memory from previous tests.\n\nAs an exception, if you want your destructor included in the fuzz test,\nthen use it in the test. Also, it’s easy to exhaust non-memory resources,\nparticularly file descriptors, and you may need to [clean those up](https://man7.org/linux/man-pages/man2/close_range.2.html)\nin order to fuzz test reliably.\n\nOf course, if the target uses [arena allocation](https://nullprogram.com/blog/2023/09/27/) then none of this\nmatters! It also makes for perfect isolation, as even addresses won’t vary\nbetween tests.\n\n### (7) Use a memory file descriptor to back named paths\n\nMany interfaces are, shall we say, *not so well-designed* and only accept\ninput from a named file system path, insisting on opening and reading the\nfile themselves. Testing such interfaces presents challenges, especially\nif you’re interested in parallel fuzzing. Fortunately there’s usually an\neasy out: Create a memory file descriptor and use its `/proc` name.\n\n```\nint fd = memfd_create(\"fuzz\", 0);\nassert(fd == 3);\nwhile (...) {\n    // ...\n    ftruncate(fd, 0);\n    pwrite(fd, buf, len, 0);\n    myprogram(\"/proc/self/fd/3\");\n}\n```\n\nWith standard input as 0, output as 1, and error as 2, I’ve assumed the\nmemory file descriptor will land on 3, which makes the test code a little\nsimpler. If it’s not 3 then something’s probably gone wrong anyway, and\naborting is the best option. If you don’t want to assume, use `snprintf`\nor whatever to construct the path name from `fd`.\n\nUsing `pwrite` (instead of `write`) leaves the file description offset at\nthe beginning of the file.\n\nThanks to the memory file descriptor, fuzz test data doesn’t land in\npermanent storage, so less wear and tear on your SSD from the occasional\nflush. Because of `/proc`, the file is unique to the process despite the\ncommon path name, so no problems parallel fuzzing. No cleanup needed,\neither.\n\nIf the program wants a file descriptor — i.e. it wants a socket because\nyou’re fuzzing some internal function — pass the file descriptor directly:\n\n```\n    myprogram(fd);\n```\n\nIf it accepts a `FILE *`, you *could* `fopen` the `/proc` path, but better\nto use `fdmemopen` to create a `FILE *` on the object:\n\n```\n    myprogram(fdmemopen(buf, len, \"rb\"));\n```\n\nNote how, per (6), we don’t need to bother with `fclose` because it’s not\nassociated with a file descriptor.\n\n### (8) Configure the target for smaller buffers\n\nA common sight in [diseased programs](http://catb.org/jargon/html/C/C-Programmers-Disease.html) are “generous” fixed buffer\nsizes:\n\n```\n#define MY_MAX_BUFFER_LENGTH 65536\n\nvoid example(...)\n{\n    char path[PATH_MAX];  // typically 4,096\n    char buf[MY_MAX_BUFFER_LENGTH];\n    // ...\n}\n```\n\nThese huge buffers tend to hide bugs. Turn those stones over! It takes a\nlot of fuzzing time to max them out and excite the unhappy paths — or the\nsuper-unhappy paths, overflows. Better if the fuzz test can reach worst\ncase conditions quickly and explore the execution paths out of it.\n\nSo when you see these, cut them way down, possibly using (3). Change 65536\nto, say, 16 and see what happens. If fuzzing finds a crash on the short\nbuffer, typically extending the input to crash on the original buffer size\nis straightforward, e.g. repeat one of the bytes even more than it already\nrepeats.\n\n### Conclusion and samples\n\nHopefully something here will help you catch a defect that would have\notherwise gone unnoticed. Even better, perhaps awareness of these fuzzing\ntechniques will prevent the bug in the first place. Thanks to my template,\nsome solid tooling, and the know-how in this article, I can whip up a fuzz\ntest in a couple of minutes. But that ease means I discard it as just as\ncasually, and so I don’t take time to capture and catalog most. If you’d\nlike to see some samples, [I do have an old, short list](https://web.archive.org/web/20260630141357/https://old.reddit.com/r/C_Programming/comments/15wouat/i_need_to_fuzz_my_program_but_i_have_never_done/jx2ld4a/). Perhaps\nafter another kiloproject of fuzz testing I’ll pick up more techniques.\n","body_html":"<p>Fuzz testing is incredibly effective for mechanically discovering software\ndefects, yet remains underused and neglected. Pick any program that must\ngracefully accept complex input, written <em>in any language</em>, which has not\nyet been been fuzzed, and fuzz testing usually reveals at least one bug.\nAt least one program currently installed on your own computer certainly\nqualifies. Perhaps even most of them. <a href=\"https://danluu.com/everything-is-broken/\" rel=\"nofollow ugc noopener\">Everything is broken</a> and\nlow-hanging fruit is everywhere. After fuzz testing ~1,000 projects <a href=\"https://nullprogram.com/blog/2019/01/25/\" rel=\"nofollow ugc noopener\">over\nthe past six years</a>, I’ve accumulated tips for picking that fruit.\nThe checklist format has worked well in the past (<a href=\"https://nullprogram.com/blog/2024/12/20/\" rel=\"nofollow ugc noopener\">1</a>, <a href=\"https://nullprogram.com/blog/2023/01/08/\" rel=\"nofollow ugc noopener\">2</a>), so\nI’ll use it again. This article discusses <a href=\"https://aflplus.plus/\" rel=\"nofollow ugc noopener\">AFL++</a> on source-available\nC and C++ targets, running on glibc-based Linux distributions, currently\nthe <em>indisputable</em> best fuzzing platform for C and C++.</p>\n<p>My tips complement the official, upstream documentation, so consult them,\ntoo:</p>\n<ul><li><a href=\"https://afl-1.readthedocs.io/en/latest/tips.html\" rel=\"nofollow ugc noopener\">Performance Tips</a> on the AFL++ website</li><li><a href=\"https://lcamtuf.coredump.cx/afl/technical_details.txt\" rel=\"nofollow ugc noopener\">Technical “whitepaper” for afl-fuzz</a></li></ul>\n<p>Even if a program has been fuzz tested, applying the techniques in this\narticle may reveal defects missed by previous fuzz testing.</p>\n<h3 id=\"1-configure-sanitizers-and-assertions\">(1) Configure sanitizers and assertions</h3>\n<p>More assertions means more effective fuzzing, and sanitizers are a kind of\nautomatically-inserted assertions. By default, fuzz with both Address\nSanitizer (ASan) and Undefined Behavior Sanitizer (UBSan):</p>\n<pre><code>$ afl-gcc-fast -g3 -fsanitize=address,undefined ...</code></pre>\n<p>ASan’s default configuration is not ideal, and should be adjusted via the\n<code>ASAN_OPTIONS</code> environment variable. If customized at all, AFL++ requires\nat least these options:</p>\n<pre><code>export ASAN_OPTIONS=&quot;abort_on_error=1:halt_on_error=1:symbolize=0&quot;</code></pre>\n<p>Except <code>symbolize=0</code>, <a href=\"https://nullprogram.com/blog/2022/06/26/\" rel=\"nofollow ugc noopener\">this <em>ought to be</em> the ASan default</a>. When\ndebugging a discovered crash, you’ll want UBSan set up the same way so\nthat it behaves under in a debugger. To improve fuzzing, make ASan even\nmore sensitive to defects by detecting use-after-return bugs. It slows\nfuzzing slightly, but it’s well worth the cost:</p>\n<pre><code>ASAN_OPTIONS+=&quot;:detect_stack_use_after_return=1&quot;</code></pre>\n<p>By default ASan fills the first 4KiB of fresh allocations with a pattern,\nto help detect use-after-free bugs. That’s not nearly enough for fuzzing.\nCrank it up to completely fill virtually all allocations with a pattern:</p>\n<pre><code>ASAN_OPTIONS+=&quot;:max_malloc_fill_size=$((1&lt;&lt;30))&quot;</code></pre>\n<p>In the default configuration, if a program allocates more than 4KiB with\n<code>malloc</code> then, say, uses <code>strlen</code> on the uninitialized memory, no bug will\nbe detected. There’s almost certainly a zero somewhere after 4KiB. Until I\nnoticed it, the 4KiB limit hid a number of bugs from my fuzz testing. Per\n(4), fulling filling allocations with a pattern better isolates tests when\nusing persistent mode.</p>\n<p>When fuzzing C++ and linking GCC’s libstdc++, consider <code>-D_GLIBCXX_DEBUG</code>.\nASan cannot “see” out-of-bounds accesses within a container’s capacity,\nand the extra assertions fill in the gaps. Mind that it changes the ABI,\nthough fuzz testing will instantly highlight such mismatches.</p>\n<h3 id=\"2-prefer-the-persistent-mode\">(2) Prefer the persistent mode</h3>\n<p>While AFL++ can fuzz many programs in-place without writing a single line\nof code (<code>afl-gcc</code>, <code>afl-clang</code>), prefer AFL++’s <a href=\"https://github.com/AFLplusplus/AFLplusplus/blob/stable/instrumentation/README.persistent_mode.md\" rel=\"nofollow ugc noopener\">persistent mode</a>\n(<code>afl-gcc-fast</code>, <code>afl-clang-fast</code>). It’s typically an order of magnitude\nfaster and worth the effort. Though it also has pitfalls (see (4), (5)). I\nkeep a file on hand, <code>fuzztmpl.c</code> — the progenitor of all my fuzz testers:</p>\n<pre><code>#include &lt;unistd.h&gt;\n\n__AFL_FUZZ_INIT();\n\nint main(void)\n{\n    __AFL_INIT();\n    char *src = 0;\n    unsigned char *buf = __AFL_FUZZ_TESTCASE_BUF;\n    while (__AFL_LOOP(10000)) {\n        int len = __AFL_FUZZ_TESTCASE_LEN;\n        src = realloc(src, len);\n        memcpy(src, buf, len);\n        // ... send src to target ...\n    }\n}</code></pre>\n<p>I <a href=\"https://vimhelp.org/insert.txt.html#%3Aread\" rel=\"nofollow ugc noopener\"><code>:r</code></a> this into my Vim buffer, then modify as needed. It’s a\nstripped and improved version of the official template, which itself has a\nserious flaw (see (5)). There are unstated constraints about the position\nof <code>buf</code> and <code>len</code> in the code, so if in doubt, refer to the original\ntemplate.</p>\n<h3 id=\"3-include-source-files-not-header-files\">(3) Include source files, not header files</h3>\n<p>We’re well into the 21st century. Nobody is compiling software on 16-bit\nmachines anymore. Don’t get hung up on the one translation unit (TU) per\nsource file mindset. When fuzz testing, we need at most two TUs: One TU\nfor instrumented code and one TU for uninstrumented code. In most cases\nthe latter takes the form of a library (libc, libstdc++, etc.) and we\ndon’t need to think about it.</p>\n<p>Fuzz testing typically requires only a subset of the program. Including\njust those sources straight in the template is both effective and simple.\nIn my template I put includes just <em>above</em> <code>unistd.h</code> so that the header\nisn’t visible to the sources unless they include it themselves.</p>\n<pre><code>#include &quot;src/utils.c&quot;\n#include &quot;src/parser.c&quot;\n#include &lt;unistd.h&gt;</code></pre>\n<p>I know, if you’ve never seen this before it looks bonkers. This isn’t what\nthey taught you in college. Trust me, <a href=\"https://en.wikipedia.org/wiki/Unity_build\" rel=\"nofollow ugc noopener\">this simple technique</a> will\nsave you a thousand lines of build configuration. Otherwise you’ll need to\nmanage different object files between fuzz testing and otherwise.</p>\n<p>Perhaps more importantly, you can now fuzz test <em>any arbitrary function</em>\nin the program, including static functions! They’re all right there in the\nsame TU. You’re not limited to public-facing interfaces. Perhaps you can\nskip (7) and test against a better internal interface. It also gives you\ndirect access to static variables so that you can clear/reset them between\ntests, per (4).</p>\n<p>Programs are often not designed for fuzz testing, or testing generally,\nand it may be difficult to tease apart tightly-coupled components. Many of\nthe programs I’ve fuzz tested look like this. This technique lets you take\na hacksaw to the program and substitute troublesome symbols just for fuzz\ntesting without modifying a single original source line. For example, if\nthe source I’m testing contains a <code>main</code> function, I can remove it:</p>\n<pre><code>#define main oldmain\n#  include &quot;src/utils.c&quot;\n#  include &quot;src/parser.c&quot;\n#undef main\n#include &lt;unistd.h&gt;</code></pre>\n<p>Sure, better to improve the program so that such hacks are unnecessary,\nbut most cases I’m fuzz testing as part of a drive-by review of some open\nsource project. It allows me to quickly discover defects in the original,\nunmodified program, and produces simpler bug reports like, “Compile with\nASan, open this 50-byte file, and then the program will crash.”</p>\n<h3 id=\"4-isolate-fuzz-tests-from-each-other\">(4) Isolate fuzz tests from each other</h3>\n<p>Tests should be unaffected by previous tests. This is challenging in\npersistent mode, sometimes even impractical. That means resetting all\nglobal state, even something like the internal <code>strtok</code> buffer if that\nfunction is used. Add fuzz testing to your list of reasons to eschew\nglobal variables.</p>\n<p>It’s mitigated by (1), but otherwise uninitialized heap memory may hold\ncontents from previous tests, breaking isolation. Besides interference\nwith fuzzing instrumentation, bugs found this way are wickedly difficult\nto reproduce.</p>\n<p>Don’t pass uninitialized memory into a test, e.g. an output parameter\nallocated on the stack. Zero-initialize or fill it with a pattern. If it\naccepts an arena, fill it with a pattern before each test.</p>\n<p>Typically you have little control over heap addresses, which likely varies\nacross tests and depends on the behavior previous tests. If the program\n<a href=\"https://nullprogram.com/blog/2025/01/19/#hash-hardening-bonus\" rel=\"nofollow ugc noopener\">depends on address values</a>, this may affect the results and make\nreproduction difficult, so watch for that.</p>\n<h3 id=\"5-do-not-test-directly-on-the-fuzz-test-buffer\">(5) Do not test directly on the fuzz test buffer</h3>\n<p>Passing <code>buf</code> and <code>len</code> straight into the target is the most common\nmistake, especially when fuzzing better-designed C programs, and\nparticularly because the official template encourages it.</p>\n<pre><code>    myprogram(buf, len);  // BAD!</code></pre>\n<p>While it’s a great sign the program doesn’t depend on null termination, it\ncreates a subtle trap. The underlying buffer allocated by AFL++ is larger\nthan <code>len</code>, and ASan will not detect read overflows on inputs! Instead\npass a copy sized to fit, which is the purpose of <code>src</code> in my template.\nAdjust the type of <code>src</code> as needed.</p>\n<p>If the program expects null-terminated input then you’ll need to do this\nanyway in order to append the null byte. If it accepts an “owning” type\nlike <code>std::string</code>, then it’s also already done on your behalf. With\n“non-owning” views like <code>std::string_view</code> you’ll still want to your own\nsize-fit copy.</p>\n<p>If you see a program’s checked in fuzz test using <code>buf</code> directly, make\nthis change and see if anything new pops out. It’s worked for me on a\nnumber of occasions.</p>\n<h3 id=\"6-don-t-bother-freeing-memory\">(6) Don’t bother freeing memory</h3>\n<p>In general, avoid doing work irrelevant to the fuzz test. The official\ntips say to “use a simpler target” and “instrument just what you need,”\nand keeping destructors out of the tests helps in both cases. Unless the\nprogram is especially memory-hungry, you won’t run out of memory before\nAFL++ resets the target process.</p>\n<p>If not for (1), it also helps with isolation (4), as different tests are\nless likely contaminated with uninitialized memory from previous tests.</p>\n<p>As an exception, if you want your destructor included in the fuzz test,\nthen use it in the test. Also, it’s easy to exhaust non-memory resources,\nparticularly file descriptors, and you may need to <a href=\"https://man7.org/linux/man-pages/man2/close_range.2.html\" rel=\"nofollow ugc noopener\">clean those up</a>\nin order to fuzz test reliably.</p>\n<p>Of course, if the target uses <a href=\"https://nullprogram.com/blog/2023/09/27/\" rel=\"nofollow ugc noopener\">arena allocation</a> then none of this\nmatters! It also makes for perfect isolation, as even addresses won’t vary\nbetween tests.</p>\n<h3 id=\"7-use-a-memory-file-descriptor-to-back-named-paths\">(7) Use a memory file descriptor to back named paths</h3>\n<p>Many interfaces are, shall we say, <em>not so well-designed</em> and only accept\ninput from a named file system path, insisting on opening and reading the\nfile themselves. Testing such interfaces presents challenges, especially\nif you’re interested in parallel fuzzing. Fortunately there’s usually an\neasy out: Create a memory file descriptor and use its <code>/proc</code> name.</p>\n<pre><code>int fd = memfd_create(&quot;fuzz&quot;, 0);\nassert(fd == 3);\nwhile (...) {\n    // ...\n    ftruncate(fd, 0);\n    pwrite(fd, buf, len, 0);\n    myprogram(&quot;/proc/self/fd/3&quot;);\n}</code></pre>\n<p>With standard input as 0, output as 1, and error as 2, I’ve assumed the\nmemory file descriptor will land on 3, which makes the test code a little\nsimpler. If it’s not 3 then something’s probably gone wrong anyway, and\naborting is the best option. If you don’t want to assume, use <code>snprintf</code>\nor whatever to construct the path name from <code>fd</code>.</p>\n<p>Using <code>pwrite</code> (instead of <code>write</code>) leaves the file description offset at\nthe beginning of the file.</p>\n<p>Thanks to the memory file descriptor, fuzz test data doesn’t land in\npermanent storage, so less wear and tear on your SSD from the occasional\nflush. Because of <code>/proc</code>, the file is unique to the process despite the\ncommon path name, so no problems parallel fuzzing. No cleanup needed,\neither.</p>\n<p>If the program wants a file descriptor — i.e. it wants a socket because\nyou’re fuzzing some internal function — pass the file descriptor directly:</p>\n<pre><code>    myprogram(fd);</code></pre>\n<p>If it accepts a <code>FILE *</code>, you <em>could</em> <code>fopen</code> the <code>/proc</code> path, but better\nto use <code>fdmemopen</code> to create a <code>FILE *</code> on the object:</p>\n<pre><code>    myprogram(fdmemopen(buf, len, &quot;rb&quot;));</code></pre>\n<p>Note how, per (6), we don’t need to bother with <code>fclose</code> because it’s not\nassociated with a file descriptor.</p>\n<h3 id=\"8-configure-the-target-for-smaller-buffers\">(8) Configure the target for smaller buffers</h3>\n<p>A common sight in <a href=\"http://catb.org/jargon/html/C/C-Programmers-Disease.html\" rel=\"nofollow ugc noopener\">diseased programs</a> are “generous” fixed buffer\nsizes:</p>\n<pre><code>#define MY_MAX_BUFFER_LENGTH 65536\n\nvoid example(...)\n{\n    char path[PATH_MAX];  // typically 4,096\n    char buf[MY_MAX_BUFFER_LENGTH];\n    // ...\n}</code></pre>\n<p>These huge buffers tend to hide bugs. Turn those stones over! It takes a\nlot of fuzzing time to max them out and excite the unhappy paths — or the\nsuper-unhappy paths, overflows. Better if the fuzz test can reach worst\ncase conditions quickly and explore the execution paths out of it.</p>\n<p>So when you see these, cut them way down, possibly using (3). Change 65536\nto, say, 16 and see what happens. If fuzzing finds a crash on the short\nbuffer, typically extending the input to crash on the original buffer size\nis straightforward, e.g. repeat one of the bytes even more than it already\nrepeats.</p>\n<h3 id=\"conclusion-and-samples\">Conclusion and samples</h3>\n<p>Hopefully something here will help you catch a defect that would have\notherwise gone unnoticed. Even better, perhaps awareness of these fuzzing\ntechniques will prevent the bug in the first place. Thanks to my template,\nsome solid tooling, and the know-how in this article, I can whip up a fuzz\ntest in a couple of minutes. But that ease means I discard it as just as\ncasually, and so I don’t take time to capture and catalog most. If you’d\nlike to see some samples, <a href=\"https://web.archive.org/web/20260630141357/https://old.reddit.com/r/C_Programming/comments/15wouat/i_need_to_fuzz_my_program_but_i_have_never_done/jx2ld4a/\" rel=\"nofollow ugc noopener\">I do have an old, short list</a>. Perhaps\nafter another kiloproject of fuzz testing I’ll pick up more techniques.</p>","headings":[{"level":3,"text":"(1) Configure sanitizers and assertions","id":"1-configure-sanitizers-and-assertions"},{"level":3,"text":"(2) Prefer the persistent mode","id":"2-prefer-the-persistent-mode"},{"level":3,"text":"(3) Include source files, not header files","id":"3-include-source-files-not-header-files"},{"level":3,"text":"(4) Isolate fuzz tests from each other","id":"4-isolate-fuzz-tests-from-each-other"},{"level":3,"text":"(5) Do not test directly on the fuzz test buffer","id":"5-do-not-test-directly-on-the-fuzz-test-buffer"},{"level":3,"text":"(6) Don’t bother freeing memory","id":"6-don-t-bother-freeing-memory"},{"level":3,"text":"(7) Use a memory file descriptor to back named paths","id":"7-use-a-memory-file-descriptor-to-back-named-paths"},{"level":3,"text":"(8) Configure the target for smaller buffers","id":"8-configure-the-target-for-smaller-buffers"},{"level":3,"text":"Conclusion and samples","id":"conclusion-and-samples"}]}}