<div dir="ltr"><div dir="ltr">Em qui., 3 de out. de 2024 às 05:46, Maurizio Cimadamore <<a href="mailto:maurizio.cimadamore@oracle.com">maurizio.cimadamore@oracle.com</a>> escreveu:<br></div><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><u></u>
<div>
<p>On 02/10/2024 23:58, Anastasiya
Lisitskaya wrote:<br></p>
<blockquote type="cite">
<div dir="ltr">
<div dir="ltr">Hi,
<div><br>
</div>
<div>It is very helpful! </div>
<div><br>
</div>
So, if I want to use data from the heap without extra copying
to off-heap (native MemorySegment), should using String be
avoided? It seems there is no way to use a String without
copying, as we can't guarantee a trailing null terminator.<br>
</div>
</div>
</blockquote>
I'm afraid that's the case. The Java String API does not concern
with string terminators because, in Java, all strings have a size.
In C that's not the case - so in general you need to append a
terminator, and that will involve some degree of copying.<br>
<blockquote type="cite">
<div dir="ltr">
<div dir="ltr"><br>
One thing still concerns me: is processing an unterminated
string unpredictable? Only one test from my suite fails
(returning this extra symbol or crashing).</div>
</div>
</blockquote>
<p>Processing an unterminated string leads to undefined behavior.
Effectively, your program is scanning _past_ the contents of your
string, in search for a zero. Because of the way some system calls
work (e.g. malloc) it is likely that a zero will be found more or
less where expected. But that behavior is OS/platform dependent
and absolutely cannot be relied upon.</p></div></blockquote><div><br></div><div>If you have control of the native code and are able to change its API, this is a great opportunity to add a size or length companion parameter to the char* parameter, avoiding this problem entirely.</div><div>This change is justified for memory safety (explicit bounds checking) and performance (compute / discover the bounds only once).</div><div> <br></div></div><span class="gmail_signature_prefix">-- </span><br><div dir="ltr" class="gmail_signature"><div dir="ltr"><div>Pedro Lamarão</div></div></div></div>