Achieving memory safety
There is a push towards memory safety from governments and other organizations. This makes sense as a huge share of bugs is memory related.
This article describes how the memory safety of the high level open source programming language Seed7 has been improved in the release 2026-07-11. This release contains 9 months of work and consists of 1029 commits. Seed7 is based on my diploma thesis and my PhD thesis, and is the result of decades of work.
My definition of memory safety
A memory safe language must ensure that it is impossible to read or change an arbitrary place in memory (inside the process or outside). Beyond that there should be protection against stack overflow, buffer overflow, buffer over-read, use after free, null pointer dereference, using uninitialized memory and double free.
Either these things are guaranteed by the language, or every developer must manually handle them. Non-memory-safe languages shift burden from the language implementation to the developers.
Nowadays many languages consider themselves as memory safe. But if a language allows calling C functions directly it cannot be considered memory safe because C is not memory safe. Reading or changing an arbitrary place in memory is not memory safe either. It seems that some definitions of memory safety are tailored to sell a language as memory safe. I think that a strict definition of memory safety should come first and the language should be designed to fulfill this definition. Otherwise memory safety is just a marketing term.
If features are omitted every language can claim to be memory safe. For systems programming languages, which usually call C functions and do unsafe things with pointers I will not go into details what could be omitted to make it memory safe. Rust is an exception because it allows calling C function only from unsafe parts.Current situation
Rust is memory safe if no unsafe parts are used. Java is memory safe unless JNI or FFM are used. Interpreted languages are usually memory safe if no calls to C functions are done.
C and C++ are not memory safe and there are several languages which aim to replace them. For example, Rust, Go, Zig, Odin, C3, Nim, Vlang, and Jai. Except for Rust these languages are not memory safe. Yes, these languages introduce concepts to avoid a lot of footguns, but they are not 100% memory safe.
Seed7 is memory safe and there are no unsafe parts. A Seed7 function cannot read secret data stored somewhere in your program. Seed7 is a general-purpose language that can be used for portable systems programming. It provides strict safety guarantees without needing low-level features.
How memory safety is achieved
In languages supporting pointers the effort to achieve memory safety is high:
- Rust checks at compile-time with the borrow checker and with lifetimes.
- Fil-C checks at run-time and panics if memory safety is violated.
Seed7 does not support pointers so they cannot be used to read or change an arbitrary place in memory. The index bounds of arrays, strings, etc. are checked in Seed7. So indexing into arrays or strings out of bounds does not allow reading and changing arbitrary places in memory. Direct calls to C functions are prohibited in Seed7 as well. So all the dangerous things that C can do are not available. These precautions make it impossible to read or change an arbitrary place in memory.
Seed7 uses automatic memory management without a garbage collection process that interrupts normal program execution. Memory used by local variables and parameters is automatically freed, when a function is left. Memory allocated for intermediate results is freed automatically in a stack like manner. The memory of strings, bigIntegers, bitsets, arrays, hashes and bstrings is referenced just once. Objects and other data which needs to be referenced several times use reference counting. This data is freed when the reference counter reaches zero.
Containers (array, hash, etc.) own their content. If something is put into a container it must be copied. For objects, copying is highly efficient as it just increments a reference counter. The ownership allows containers to free their content when they are freed. Without pointers it is impossible to reference elements of a container. If a container is freed no stale pointers can refer to freed data.
Reference parameters borrow the reference to memory until the function is left. No copying of memory is necessary and the owner of the actual parameter is in charge of freeing the memory. A borrow checker checks if two reference parameters refer to the same data. The borrow checker checks also if a reference parameter and a global variable refer to the same data. How the Seed7 borrow checker works will be covered in a future article. Finally Seed7 protects against stack overflow as well.
Interfacing the outside world
On one hand, Seed7 programs cannot call C functions directly. On the other hand, programs need to interface with the outside world to open files, handle networking, perform database queries, render graphics, and manage other system-level tasks.
To bridge this gap, parts of the Seed7 standard library are written in C. The difference between this and the unsafe code parts found in some private programs is that the source code of the Seed7 library is publicly available under the LGPL license. This allows everyone to audit and inspect the Seed7 runtime, which ultimately improves code quality and guarantees memory safety.
Seed7 allows programs to interface with different operating systems, databases, and graphics libraries without modifying the Seed7 source code. This portability is achieved through driver libraries that balance out the differences between the underlying platforms.
The world of C and the world of Seed7 are completely different. E.g., C strings are null-terminated, whereas Seed7 strings encode Unicode code points directly without null-termination. Because of these differences, the Seed7 runtime functions convert data, allocate and free memory, handle error codes, and manage various other tasks behind the scenes.
System resources, such as files, sockets, and database connections, must be closed. The Seed7 runtime closes these resources automatically when the associated data is freed. They can also be closed explicitly. If a resource is used after being explicitly closed, an exception is raised.
Primitive actions
The connection between Seed7 code and C code is established using primitive actions. For example:
const func clib_file: openClibFile (in string: path,
in string: mode)
is action "FIL_OPEN";
Primitive actions have a name and map to an underlying C function. Seed7 operators are implemented with primitive actions as well:
const func float: (in float: summand1) +
(in float: summand2) is action "FLT_ADD";
The C function implementing a primitive action expects parameters of specific types.
In case of openClibFile, these would be string values.
On the C side, a Seed7 string corresponds to a pointer referencing
a struct that holds the actual string data.
On the Seed7 side, the type system ensures that primitive actions are never invoked with wrong parameter types:
*** tst1.sd7(7):57: Match for openClibFile(12345, 67890) failed
aFile := openClibFile(12345, 67890);
However, a developer could erroneously define openClibFile with integer parameters:
const func clib_file: openClibFile (in integer: path,
in integer: mode)
is action "FIL_OPEN";
Without safety checks, this would force the C function corresponding to FIL_OPEN to
be called with integer arguments instead of string references.
These integer parameters would then be misinterpreted as pointers, triggering memory safety violations.
The improvements introduced in Seed7 release 2026-07-11 prevent this scenario:
*** tst2.sd7(3):42: Declaration of "openClibFile (
val integer: path, val integer: mode)" failed
const func clib_file: openClibFile (in integer: path,
Now primitive actions carry information about which parameter category they accept and which parameter category they return.
Assuring memory safety of Seed7
In principle, it is possible to formally prove the memory safety of a language. Languages are usually implemented in a systems programming language (such as C, C++, or Rust). Consequently, the actual implementation does not automatically inherit the guarantees of the theoretical proof. Therefore, in addition to a formal proof of the language specification, a proof of the actual implementation is needed as well. In this article, we just cover the memory safety of the actual implementation.
Seed7 is implemented in C and C is not memory safe. So it is not easy to guarantee the memory safety of Seed7.
So it is necessary to improve the C code of Seed7 such that the end result is memory safe. All places where the implementation is not memory safe must be found and improved.
There are three areas where C code needs to be examined:
- The interpreter
- The C code generated by the Seed7 compiler
- The part of the runtime library written in C
Most of the Seed7 runtime library is written in Seed7 itself (and is therefore inherently safe).
Test suite
The Seed7 test suite consists of over 200,000 lines of Seed7 code. The tests cover functionality of the Seed7 language and its run-time libraries. Every time an error is found corresponding tests are added to the test suite. The test suite contains also code snippets which the Seed7 compiler can optimize. This way the compiler optimizations are checked as well. When the test suite runs it checks interpreter and compiler. The compiler is checked when it is interpreted and when the compiler executable is used. Every program from the test suite is compiled with different optimization settings.
The Seed7 run-time has its own memory management (arenas, free-lists, etc.). Tools like Valgrind, sanitizers and Fil-C can only find memory errors if malloc(), realloc() and free() are used directly. When searching for memory errors, the arenas and free-lists of the Seed7 memory management system must be deactivated. This triggers a slowdown by a factor of up to two when the test suite runs.
Code coverage
Gcc supports mechanisms to do code coverage. This is used to determine how much of the Seed7 compiler is used by the test suite. New tests are added to increase the compilers code coverage.
Tools
There are several tools helping to find dangerous places. Each of the tools below were used to run the test suite.
Valgrind
Valgrind is a virtual machine. It can execute executables and is capable of finding all kinds of memory errors. No instrumentation code is added to the executable. The source code of a program is not needed, but it helps if it has been compiled with debugging information. Valgrind can find reads or writes past the end of allocated memory, use after free, double free, freeing non-heap memory, use of uninitialized memory and memory leaks. Since the code does not execute directly on the hardware there is a slowdown.
Sanitizers
Sanitizers add code to a program to do checks at run-time. They work with "redzones" to detect out-of-bounds access. If an out-of-bound access happens you get a panic. Off by one errors in memory access are reliably caught. But if the access goes beyond the "redzone" there is no protection. This way data in some other "whitezone" could be read or written. The clang sanitizer is used with the following options:
-fsanitize=address,integer,undefined -fno-sanitize=unsigned-integer-overflow,unsigned-shift-base,shift
It was necessary to change some things to support the sanitizer. The simplified data structure for strings is:
typedef struct striStruct {
memSizeType size;
strElemType mem[1];
} striRecord;
An empty string does not need the mem element.
This means the size of an empty string is smaller than the size of striRecord.
The sanitizer does not like this fact.
For this special case the data structure emptyStriRecord has been introduced.
Fil-C
Fil-C is a C compiler and run-time library which turns C into a memory safe language. Fil-C works with invisible pointer capabilities. Every pointer has a lower bound and an upper bound. So jumping over a "redzone" to the next allowed area is not possible. The memory allocation and checking for allowed ranges works with units of 16 bytes. So off by one errors in memory access might not be caught:
char *a;
a = (char *) malloc(1);
a[1] = 'b';
printf("%c\n", a[1]);
return 0;
Fil-C allows a cast from int to pointer,
but these pointers lack the invisible pointer capabilities
and therefore cannot be used to reach the data they point to.
The Seed7 compiler previously used such int to pointer casts at certain places.
Pointers were cast to genericType (an unsigned int with the pointer size) and later cast back to the same pointer type.
These casts have been removed and now the union rtlValueUnion with elements for every pointer type is used instead.
Instead of code like
intType bigCmpGeneric (const genericType value1,
const genericType value2)
{ /* bigCmpGeneric */
return bigCmp(
((const_rtlObjectType *) &value1)->value.bigIntValue,
((const_rtlObjectType *) &value2)->value.bigIntValue);
} /* bigCmpGeneric */
the following code is used
intType bigCmpValue (const rtlValueUnion value1,
const rtlValueUnion value2)
{ /* bigCmpValue */
return bigCmp(value1.bigIntValue, value2.bigIntValue);
} /* bigCmpValue */
By switching to rtlValueUnion, the original pointers are never cast into non-pointer types.
This allows Fil-C to check the invisible pointer capabilities.
The Seed7 test suite worked okay but running it with Fil-C was extremely time consuming. Since X11 and ncurses are not supported by Fil-C, not everything could be tested. When running the test suite the slowdown was significant (approx. one week vs. 15 minutes). Most of the slowdown came from the filcc compiler. The filcc compiler became extremely slow. Some compilations took 15 hours.
ChatGPT Codex
Codex was asked multiple times to find places where a segmentation fault could happen. Codex has a list of potentially dangerous C functions and complains when they are used. Codex came up with many findings where extreme corner cases may trigger an error. Sometimes it complains about obviously correct code. E.g., If on a 32-bit computer the command-line exceeds 4GB, the length computation will overflow. It is highly doubtful that on a 32-bit computer anything can have the size of 4GB.
Using different C compilers
Different C compilers are used to compile Seed7 and to run the test suite. Even ones which are not officially supported such as Watcom C and Pelles C. The tests are done with the highest warning levels. The various C compilers complain about different things. These complaints lead to better code.
Supporting different platforms
Seed7 supports Linux, macOS, FreeBSD, OpenBSD, Unix, Windows and programs running in the browser. Reintroducing the support for the operating system DOS (with DJGPP) helped to find corner cases.
The Seed7 community
This is an important part. People write real world applications with Seed7 and use it in unforeseen ways. This leads to fixes and improvements of the test suite. Most issues found by the community are not memory safety related, but some are.
Checking for stack overflows
Both Linux/BSD/MacOS/Unix and Windows provide mechanisms to recognize a stack overflow.
- Under Linux/BSD/MacOS/Unix an alternate signal stack must be used and a stack overflow triggers a SIGSEGV signal.
- Under Windows a stack overflow handler must be used and after a stack overflow has been handled the guard pages must be restored.
Now a program with an endless recursion like:
$include "seed7_05.s7i";
const proc: main is func
begin
main;
end func;
triggers a MEMORY_ERROR:
*** Uncaught exception MEMORY_ERROR raised at sigutl.c(355)
A loophole introduced by operating systems
My definition of memory safety is about what a program can do by itself. Nothing provided by the Seed7 core language or its run-time libraries should break memory safety. The environment surrounding a program is not covered by this definition of memory safety.
For example, if a program is executed in a virtual machine, this virtual machine can read or change an arbitrary place in the process memory. The virtual machine could even forward this capability to the process it runs. So the program would be able to break memory safety with the help of the virtual machine. This is beyond my definition of memory safety.
The /proc file-system provides access to the memory of the current process.
This can be used to read or change an arbitrary place in the process memory.
In my view, this is a severe security loophole introduced by the operating system.
As in the example with the virtual machine, the environment (the operating system)
breaks memory safety. The /proc file-system allows a (third-party)
library function to inspect the secret password, even if a memory-safe
programming language is used.
This loophole can only be closed with the help of the operating system.
Blocking the possibility to open files in /proc will not be sufficient,
since a process (e.g., a shell) can be started that reads or changes the memory
via /proc.
A Linux program which calls prctl(PR_SET_DUMPABLE, 0) blocks the
ability to access its own memory via /proc. Calling
prctl(PR_SET_DUMPABLE, 0) on a process prevents unprivileged
subprocesses from accessing the parent's memory via /proc
as well. Even if the child process calls prctl(PR_SET_DUMPABLE, 1),
it will still not be able to access the parent's memory via /proc.
Standard Linux distributions do not ship with pre-installed SUID-root utilities
that allow an unprivileged parent to bypass PR_SET_DUMPABLE=0.
The Seed7 interpreter has been changed to call prctl(PR_SET_DUMPABLE, 0)
at startup. The Seed7 compiler has been changed to generate programs
which invoke prctl(PR_SET_DUMPABLE, 0) at startup.
These changes are not part of the 2026-07-11 release.
Tests confirmed that these changes block access to /proc/self/mem.
Summary
Memory safety is not just a marketing term; it is the product of strict design decisions backed by rigorous engineering. By eliminating pointers, direct calls to C functions, and unsafe parts, Seed7 removes the standard vectors for memory exploits. A 200,000-line test suite, the utilization of verification tools, and comprehensive code audits conducted by both humans and AI have significantly enhanced the memory safety of the 2026-07-11 release.