Sub topic 9
Working with C strings
A C string is a run of bytes ending in a zero byte, and C passes it around as a char *. The FFM API has no string type. A C string is a MemorySegment that happens to hold encoded text followed by a terminator. This chapter covers both directions: giving Java strings to C, and reading strings that C gives back.
It assumes you can build a downcall handle from a Linker, a SymbolLookup and a FunctionDescriptor, and that you know how arenas control lifetime.
The examples target Java 22, where the string methods are named allocateUtf8String, getUtf8String and setUtf8String. Java 23 and later renamed them, as the table below shows.
What a C string looks like in memory
The Java string "héllo" has 5 characters. In UTF-8 the é takes two bytes, so the encoded text is 6 bytes. C needs one more byte for the terminator, so the segment is 7 bytes long.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Byte | `h` | `é` (first byte) | `é` (second byte) | `l` | `l` | `o` | `0` |
This explains most string bugs. A C function that counts bytes, such as strlen, reports 6 for this string, not 5. A buffer sized from String.length() is too small for any text outside ASCII.
The string methods
Three methods handle the conversion. They always use UTF-8 and always add or expect the terminating zero byte.
| Task | Java 22 | Java 23 and later |
|---|---|---|
| Allocate a new C string | `allocator.allocateUtf8String(s)` | `allocator.allocateFrom(s)` |
| Read a C string | `segment.getUtf8String(offset)` | `segment.getString(offset)` |
| Write a C string into existing memory | `segment.setUtf8String(offset, s)` | `segment.setString(offset, s)` |
Arena implements SegmentAllocator, so you call the allocation method directly on an arena. The new segment lives as long as that arena. Java 23 and later also have overloads that take a Charset, for native APIs that don't use UTF-8.
The Java 22 allocateUtf8String allocates exactly the encoded length plus one byte. A segment for "Hello, FFM" has size 11.
Passing a string to C
The strlen call from earlier in this tutorial is the simplest case. This version shows that C counts bytes and not characters:
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class ByteCount {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
MethodHandle strlen = linker.downcallHandle(
linker.defaultLookup().find("strlen").orElseThrow(),
FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS));
String text = "h\u00e9llo";
try (Arena arena = Arena.ofConfined()) {
MemorySegment cString = arena.allocateUtf8String(text);
long bytes = (long) strlen.invokeExact(cString);
System.out.println(text.length() + " chars, " + bytes + " bytes, segment size " + cString.byteSize());
}
}
}The output is 5 chars, 6 bytes, segment size 7.
Two details matter here. First, the parameter is declared as ValueLayout.ADDRESS, and you pass the segment itself. The linker passes the segment's start address to C. Second, the segment must stay alive for the whole call. Here the arena closes after the call, which is correct. If C stored the pointer for later use, a confined arena closed after the call would leave C holding a dangling address.
Embedded zero characters
C stops reading at the first zero byte. If a Java string contains '\u0000', the C function sees only the text before it. Check for this when strings come from untrusted input and the C side makes security decisions.
Reading a string that C returns
A function that returns char * gives you an address, and the FFM API cannot know how long the memory behind it is. A returned ADDRESS therefore becomes a zero-length segment. Calling getUtf8String(0) on it throws IndexOutOfBoundsException.
You have to tell the API how far it may read. MemorySegment.reinterpret(long) attaches a new size to the address. It is a restricted method, so it needs native access to be enabled, which the next chapter covers. For a NUL-terminated string you don't know the length in advance, so the usual choice is Long.MAX_VALUE. The read still stops at the terminator.
The C function getenv returns a pointer to the value of an environment variable, or NULL if it isn't set:
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class EnvDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
MethodHandle getenv = linker.downcallHandle(
linker.defaultLookup().find("getenv").orElseThrow(),
FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS));
try (Arena arena = Arena.ofConfined()) {
MemorySegment name = arena.allocateUtf8String("PATH");
MemorySegment result = (MemorySegment) getenv.invokeExact(name);
if (result.address() == 0) {
System.out.println("PATH is not set");
} else {
String value = result.reinterpret(Long.MAX_VALUE).getUtf8String(0);
System.out.println(value);
}
}
}
}Always test for the null address first. NULL comes back as a segment whose address is 0. Calling reinterpret and reading from it would crash the JVM, not throw a Java exception.
Who owns the returned memory
Reading a returned pointer is separate from owning it. The getenv result belongs to the C runtime. Do not free it, and copy it into a Java String before anything modifies the environment.
Some functions, such as strdup, return memory from malloc. You must release that memory with free, which you also call through a downcall handle. The documentation of each C function says which case applies. reinterpret has an overload that takes a cleanup action, which can call free when an arena closes:
MemorySegment owned = result.reinterpret(Long.MAX_VALUE, arena, seg -> free(seg));Here free stands for a helper that invokes the free downcall handle. Use this form when the arena should own the returned memory.
Giving C a buffer to fill
Many C functions take a buffer and a capacity and write a string into it. This is the safest pattern, because Java allocates the memory, so the segment has a known size and needs no reinterpret.
getcwd(char *buf, size_t size) writes the current directory into buf. It returns buf on success and NULL on failure. It exists on Linux and macOS but not on Windows.
import java.lang.foreign.Arena;
import java.lang.foreign.FunctionDescriptor;
import java.lang.foreign.Linker;
import java.lang.foreign.MemorySegment;
import java.lang.foreign.ValueLayout;
import java.lang.invoke.MethodHandle;
public class CwdDemo {
public static void main(String[] args) throws Throwable {
Linker linker = Linker.nativeLinker();
MethodHandle getcwd = linker.downcallHandle(
linker.defaultLookup().find("getcwd").orElseThrow(),
FunctionDescriptor.of(ValueLayout.ADDRESS, ValueLayout.ADDRESS, ValueLayout.JAVA_LONG));
try (Arena arena = Arena.ofConfined()) {
MemorySegment buffer = arena.allocate(4096);
MemorySegment result = (MemorySegment) getcwd.invokeExact(buffer, buffer.byteSize());
if (result.address() == 0) {
System.out.println("getcwd failed");
} else {
System.out.println(buffer.getUtf8String(0));
}
}
}
}Passing buffer.byteSize() as the capacity keeps the two values in sync. If you later change the allocation, the capacity argument follows. Reading from buffer uses the segment's own bounds, so no restricted method is involved. Here the size_t parameter is modeled as JAVA_LONG, which is correct on 64-bit platforms.
Run any of these files with the source launcher:
java --enable-native-access=ALL-UNNAMED CwdDemo.javaStrings inside structs and at offsets
setUtf8String(offset, string) and getUtf8String(offset) take a byte offset, so you can place a string in the middle of a larger segment. The write checks bounds. If the encoded text plus the terminator doesn't fit between the offset and the end of the segment, you get an IndexOutOfBoundsException and nothing is written.
This matters for structs with fixed char name[32] fields. Describe the field as a sequence of 32 bytes, then write into it at the field's offset. A name longer than 31 bytes in UTF-8 fails the bounds check. That is the behavior you want, because C code would silently overflow the field.
A char * field inside a struct is different. It holds an address, so you allocate the string separately and store its segment with an ADDRESS layout. The string's arena must outlive every use of the struct.
Common mistakes
- Sizing buffers from
String.length(). Use the UTF-8 byte count plus one for the terminator. - Reading a returned pointer without
reinterpret. The zero-length segment throwsIndexOutOfBoundsException. - Skipping the null check. A
NULLresult followed byreinterpretand a read crashes the process. - Closing the arena before C is done with the string. This is a use-after-free if C kept the pointer.
- Freeing memory you don't own, or leaking memory you do. Check the C documentation for each function.
- Using a method name from the wrong release.
allocateUtf8Stringdoes not exist in Java 23 and later, andallocateFromdoes not exist in Java 22.
Exercise
A C function declared as const char *version(void) returns a pointer to a static string. A Java developer writes ((MemorySegment) version.invokeExact()).getUtf8String(0) and gets an IndexOutOfBoundsException. What is the cause, and what is the fix? Does the developer need to free the result?
Show answer
The returned ADDRESS becomes a zero-length segment, so reading at offset 0 is out of bounds. Fix it by calling reinterpret(Long.MAX_VALUE) on the result first, after checking that its address is not 0 (NULL), then calling getUtf8String(0). The string is static and owned by the C library, so the developer must not free it.
Exercise
You allocate arena.allocateUtf8String("naïve"). What is the segment's byteSize, and why does it differ from the string's length?
Show answer
The byteSize is 7. "naïve" has 5 characters, but ï takes two bytes in UTF-8, giving 6 bytes of text, plus one terminating zero byte. The segment size counts bytes, not characters.