Skip to content

Zero length, non-zero capacity string passed to C function as cstring crashes when being written to #26853

Done

Description

@cromachina

Nim Version

Nim Compiler Version 2.4.0 [Linux: amd64]
gcc (GCC) 16.2.0

Description

If a zero length string with non-zero capacity is passed to a C function as a cstring, such as to be written into below the capacity, but potentially above the length, of the string, the program will SIGSEGV. This does not seem to happen to non-zero length strings with the same capacity. Maybe it's a zero length string optimization gone wrong? I'm assuming capacity is the absolute size of the underlying allocated buffer.

The scenario that this happens for me is initializing a user input text editing field from a C library and the previously supplied user value was an empty string. I'm using a fixed sized string as a buffer for this input text field.

Tested with --mm orc, arc, and atomicArc
Tested compiler targets c and cpp

import std/strformat

# Print info about the string
proc str_info(msg, str: string) =
    echo fmt"{msg}: '{str}', len: {str.len}, capacity: {str.capacity}"

# Mimics a C function that sets a string to something, like a text input field (like in Imgui)
# buffer_size would tell the C function how long the string is, so it doesn't overrun the capacity (not used here).
proc get_user_input_c(text: cstring, buffer_size: csize_t) =
    # CRASH somewhere in here if text is backed by a string of len = 0 but capacity = 256
    let text_ptr = text.addr
    # The user types and the C side pokes into this string.
    text_ptr[0] = 'a'
    text_ptr[1] = 's'
    text_ptr[2] = 'd'
    text_ptr[3] = 'f'
    text_ptr[4] = '\0'

# Fixed buffer for our C function to write into.
var fixed_buffer = newStringOfCap(256)

# Called once, somewhere, when the user wants to open the dialog with an initial value.
proc init_dialog(text: string) =
    fixed_buffer.setLen(0) # Capacity still 256, unless the capacity value is lying!
    fixed_buffer.add(text)

# Would run in a loop to poll new for text.
proc show_dialog() =
    str_info("fixed_buffer", fixed_buffer)
    var cstr = fixed_buffer.cstring
    get_user_input_c(cstr, fixed_buffer.capacity().csize_t)
    # Example: if an "Okay" button is pressed, retrieve the value and do something with it:
    fixed_buffer.setLen(cstr.nimCStrLen())
    let user_value = $fixed_buffer
    str_info("user_value", user_value)

# String with len larger than what the c function sets (copied to 256 capacity buffer)
var okay_string = "hello world"
init_dialog(okay_string)
show_dialog()

# String with len smaller than what the c function sets (copied to 256 capacity buffer)
var okay_string_2 = "foo"
init_dialog(okay_string_2)
show_dialog()

# String with len 0 (copied to 256 capacity buffer.)
var broken_string = ""
init_dialog(broken_string)
show_dialog()

Current Output

fixed_buffer: 'hello world', len: 11, capacity: 256
user_value: 'asdf', len: 4, capacity: 4
fixed_buffer: 'foo', len: 3, capacity: 256
user_value: 'asdf', len: 4, capacity: 4
fixed_buffer: '', len: 0, capacity: 256
Traceback (most recent call last)
test.nim(50) test
test.nim(31) show_dialog
test.nim get_user_input_c
SIGSEGV: Illegal storage access. (Attempt to read from nil?)
Segmentation fault         (core dumped) ./test

Expected Output

fixed_buffer: 'hello world', len: 11, capacity: 256
user_value: 'asdf', len: 4, capacity: 4
fixed_buffer: 'foo', len: 3, capacity: 256
user_value: 'asdf', len: 4, capacity: 4
fixed_buffer: '', len: 0, capacity: 256
user_value: 'asdf', len: 4, capacity: 4

Known Workarounds

Allocating a new string of my max fixed length every time I want to initialize my buffer alleviates the issue:

proc init_dialog(text: string) =
    fixed_buffer = newString(256)
    fixed_buffer.add(text)

This looks strange, but it seems to not crash.

fixed_buffer: 'hello world', len: 267, capacity: 512
user_value: 'asdf', len: 4, capacity: 4
fixed_buffer: 'foo', len: 259, capacity: 512
user_value: 'asdf', len: 4, capacity: 4
fixed_buffer: '', len: 256, capacity: 256
user_value: 'asdf', len: 4, capacity: 4

Additional Information

No response

Activity

  1. cromachina commented on Nov 30, 2026

    @cromachina
    Author

    Actually the workaround doesn't work for my particular use-case. The C library is displaying the string from the empty start, despite how it's shown when passed to fmt.

  2. cromachina commented on Nov 30, 2026

    @cromachina
    Author

    Okay, found a workaround that actually works, I forced the len to be non-zero in the empty string case by pushing a null char into the string:

    proc init_dialog(text: string) =
        fixed_buffer.setLen(0)
        if text.len == 0:
            fixed_buffer.add('\0')
        else:
            fixed_buffer.add(text)
    fixed_buffer: '', len: 1, capacity: 256
    user_value: 'asdf', len: 4, capacity: 4
    
  3. Araq commented on Dec 2, 2026

    @Araq
    Member

    Learn about prepareMutation.

  4. cromachina commented on Dec 2, 2026

    @cromachina
    Author

    Adding prepareMutation doesn't fix the crash. Also the comment for prepareMutation (which is not in the manual), says:

      # string literals are "copy on write", so you need to call
      # `prepareMutation` before modifying the strings via `addr`.
    

    However I'm copying into a newStringOfCap, which as far as I can understand, is not a string literal, despite string literals being "added" to it.

    Will you reopen this issue? It seems like there is an actual problem, prepareMutation or not.

    # Would run in a loop to poll new for text.
    proc show_dialog() =
        str_info("fixed_buffer", fixed_buffer)
        prepareMutation(fixed_buffer) # <------ HERE
        var cstr = fixed_buffer.cstring
        get_user_input_c(cstr, fixed_buffer.capacity().csize_t)
        # Example: if an "Okay" button is pressed, retrieve the value and do something with it:
        fixed_buffer.setLen(cstr.nimCStrLen())
        let user_value = $fixed_buffer
        str_info("user_value", user_value)
  5. cromachina commented on Dec 2, 2026

    @cromachina
    Author

    I've distilled the example code further (with prepareMutation included, which shouldn't change anything because there are no string literals):

    # No crash
    block:
        var str = newStringOfCap(256)
        str.setLen(1)
        prepareMutation(str)
        var cstr = str.cstring
        var str_p = cstr.addr
        str_p[10] = 'a'
    
    # Crash
    block:
        var str = newStringOfCap(256)
        # str.setLen(0) # It's already len = 0
        prepareMutation(str)
        var cstr = str.cstring
        var str_p = cstr.addr
        str_p[10] = 'a'
  6. cromachina commented on Dec 2, 2026

    @cromachina
    Author

    I'll reiterate, the entire impetus for this is that a user should be able to pass an empty cstring of some allocated capacity to C to be filled out by said C function and expect it to not crash as long as all reads and writes take place within this capacity, regardless of the set length of the owning string. You would also expect the null terminator to be placed at the end of the zero length string of interest, such that the C side may also read the string safely (and see that it is an empty string).

    I added some more workarounds which avoid using string altogether:

    proc fill_str(str: cstring) =
        var str_p = str.addr
        str_p[0] = 'a'
        str_p[1] = 'b'
        str_p[2] = 'c'
        str_p[3] = '\0'
    
    # No crash: string of cap 256, len 1
    block:
        var str = newStringOfCap(256)
        str.setLen(1)
        prepareMutation(str)
        var cstr = str.cstring
        fill_str(cstr)
        echo $cstr
    
    # No crash: stack (probably) allocated array of 256 bytes
    block:
        var str: array[256, byte]
        str[0] = 0
        var cstr = cast[cstring](str[0].addr)
        fill_str(cstr)
        echo $cstr
    
    # No crash: heap allocated 256 bytes
    block:
        var str = alloc0(256)
        defer: dealloc(str)
        var cstr = cast[cstring](str)
        fill_str(cstr)
        echo $cstr
    
    # Crash: string of cap 256, len 0
    block:
        var str = newStringOfCap(256)
        # str.setLen(0) # It's already len = 0
        prepareMutation(str)
        var cstr = str.cstring
        fill_str(cstr)
        echo $cstr
  7. cromachina commented on Dec 2, 2026

    @cromachina
    Author

    For the emulated C function, this should probably be changed

    var str_p = str.addr

    to

    var str_p = str

    It makes no difference in the result however. I'm not exactly sure what is happening when you ask for the address of a cstring, but it seems like it simply "does the right thing". Anyway the point stands that it's the "C side" touching the memory.

  8. cromachina commented on Dec 2, 2026

    @cromachina
    Author

    I took a closer look into what the compiler is actually doing and I found something suspicious during cstring conversion:

    if ssLen(s) > PayloadSize:

    Shouldn't this instead be the following?

      if capacity(s) > PayloadSize:
  9. cromachina commented on Dec 4, 2026

    @cromachina
    Author

    @Araq I think I've demonstrated sufficient proof of an actual problem for this to be reopened, if you would please reconsider.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions