Skip to content

Allocating memory

Chung Leong edited this page Nov 17, 2026 · 4 revisions

ZPX provides an allocator for allocating memory from PHP. Two kinds of memory can be obtained: persistent memory and per-request memory. During extension startup, persistent memory is returned. Per-request memory is returned while a request is being handled. The latter type is actively tracked by PHP and would be freed even if your extension fail to free it. Such occurence would still be considered leaks, however, and should be avoided during normal operation.

const php = @import("php/root.zig");

var global_text: []u8 = undefined;

pub fn moduleStartup(_: *@This(), _: php.Module.Type, _: c_int) !void {
    // allocating persistent memory
    global_text = try php.allocator.print("some text", .{});
}

pub fn requestStartup(_: *@This(), _: php.Module.Type, _: c_int) !void {
    php.print("persistent string: {s}\n", .{global_text});
}

pub fn moduleShutdown(_: *@This(), _: php.Module.Type, _: c_int) !void {
    // freeing persistent memory
    php.allocator.free(global_text);
}

pub fn @"call show"(_: *@This(), args: struct {
    string: []const u8,
}) !void {
    // allocating per-request memory
    const text = try php.allocator.print("string = {s}\n", .{args.string});
    // freeing per-request memory
    defer php.allocator.free(text);
    _ = try php.write(text);
}
<?php

show("Hello world");
persistent string: some text
string = Hello world

Out-of-memory error handling

Due to the way PHP's memory manager works, you generally don't need to worry about receiving an out-of-memory error from the PHP allocator. If an allocation operation fails due to memory limit, PHP would immediately terminate execution through a longjmp:

const std = @import("std");

const php = @import("php/root.zig");

pub fn @"call test_alloc_u8"(_: *@This()) !void {
    const slice = php.allocator.alloc(u8, std.math.maxInt(isize)) catch |err| {
        php.print("Error: {}\n", .{err}); // unreachable line
        return;
    };
    defer php.allocator.free(slice);
}
<?php

test_alloc_u8();
Fatal error: Allowed memory size of 134217728 bytes exhausted at php/Allocator.zig:26 (tried to allocate 9223372036854775807 bytes) in /home/cleong/zpx/test/wiki/allocator-out-of-mem/test.php on line 3

The only way you can trigger an out-of-memory error is by overflowing a usize:

const std = @import("std");

const php = @import("php/root.zig");

pub fn @"call test_alloc_u16"(_: *@This()) !void {
    const slice = php.allocator.alloc(u16, std.math.maxInt(usize)) catch |err| {
        php.print("Error: {}\n", .{err});
        return;
    };
    defer php.allocator.free(slice);
}
<?php

test_alloc_u16();
Error: error.OutOfMemory

Specialized allocators

String.allocator and Object.allocator are specialized allocators that acquire additional memory on top of the requested amount. This is done so that internal fields used by the Zend Engine can be attached at a later time:

data arrangement

You usually have no need to directly reference these allocators as your function handlers will receive them automatically at appropriate situations:

const std = @import("std");

const php = @import("php/root.zig");

pub fn @"call get_string"(_: *@This(), allocator: std.mem.Allocator, args: struct {
    name: []const u8,
}) ![]const u8 {
    const slice = try allocator.print("Hello, {s}!", .{args.name});
    php.print("address of allocated memory = 0x{x}\n", .{
        @intFromPtr(slice.ptr),
    });
    return slice;
}

pub fn @"call show_address"(_: *@This(), args: struct {
    string: *php.String,
}) void {
    php.print("address of string contents = 0x{x}\n", .{
        @intFromPtr(args.string.slice().ptr),
    });
}
<?php

$string = get_string("Joe");
echo "$string\n";
show_address($string);
address of allocated memory = 0x7577d9a82068
Hello, Joe!
address of string contents = 0x7577d9a82068

In the example above, the function's return value indicated that a string would be returned. ZPX has therefore elected to pass String.allocator instead of the regular one. Thanks to the extra bytes in front of the characters it was able to create a new string without allocating new memory.

String.fromOwnSlice() and Object.fromCustom() are the functions responsible for turning pre-allocated memory into actual strings and objects. When these are already created, calls would simply result in the given pointers being shifted forward by a fixed amount.

Clone this wiki locally