phobos icon indicating copy to clipboard operation
phobos copied to clipboard

Segmentation Fault in std.array when calling InPlaceAppender.ensureAddable(size_t nelems)

Open andrewlalis opened this issue 8 months ago • 1 comments

When running my program with gdb, I get the following segmentation fault:

Thread 16 "http1-test" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffcd7fa640 (LWP 33330)]
0x000055555576899b in _D3std5array__T15InPlaceAppenderTAyaZQw13ensureAddableMFNaNbNfmZv (this=..., nelems=0) at /usr/include/dmd/phobos/std/array.d:3842
3842        private void ensureAddable(size_t nelems)
(gdb) display nelems
1: nelems = 0

I don't know exactly what's happening, because the segmentation fault is being thrown as soon as this line is called:

auto headerStr = consumeUntil(inputStream, "\r\n");

where consumeUntil is defined as

/**
 * Helper function to consume string content from an input stream until a
 * certain target pattern of characters is encountered.
 * Params:
 *   inputStream = The stream to read from.
 *   target = The target at which to stop reading.
 * Returns: The string that was read, or a stream error.
 */
Either!(string, "value", StreamError, "error") consumeUntil(S)(
    S inputStream,
    string target
) if (isByteInputStream!S) {
    ubyte[1024] buffer;
    size_t idx;
    while (true) {
        auto result = inputStream.readFromStream(buffer[idx .. idx + 1]);
        if (result.hasError) return Either!(string, "value", StreamError, "error")(result.error);
        if (result.count != 1) return Either!(string, "value", StreamError, "error")(
            StreamError("Failed to read a single element", 1)
        );
        idx++;
        if (idx >= target.length && buffer[idx - target.length .. idx] == target) {
            return Either!(string, "value", StreamError, "error")(
                cast(string) buffer[0 .. idx - target.length].idup
            );
        }
        if (idx >= buffer.length) {
            return Either!(string, "value", StreamError, "error")(
                StreamError("Couldn't find target \"" ~ target ~ "\" after reading 1024 bytes.", 1)
            );
        }
    }
}

and ultimately, inputStream.readFromStream is calling BufferedInputStream.readFromStream.

andrewlalis avatar Jun 01 '25 20:06 andrewlalis

Note that I've checked and confirmed that no code inside of consumeUntil is being executed. The segmentation fault is thrown simply by attempting to call the function.

andrewlalis avatar Jun 01 '25 20:06 andrewlalis