Nim: Obtaining string address results in IndexError

Created on 22 May 2018  路  6Comments  路  Source: nim-lang/Nim

Commit: c12726d41e7df20bce452b6d7f8959d8b9e401a9

This code now produces IndexError, even though I think it shouldn't?

var s = ""
echo unsafeAddr(s[0])

Most helpful comment

Isn't the problem here that we don't offer a separate call returning the starting address of the string? I don't see why the combination unsafeAddr(s[X]) should be blessed when s[X] doesn't denote a legal location. Having a starting address allows you to do any kind of pointer arithmetic yourself.

All 6 comments

From the changelog:

Accessing the binary zero terminator in Nim's native strings is now invalid. Internally a Nim string still has the trailing zero for zero-copy interoperability with cstring. Compile your code with the new switch --laxStrings:on if you need a transition period.

This always was an edge-case, not that this code never worked for seq. This code should be written as cstring(s).

@trustable-code there is no _accessing_ in the sample I provided, so the changelog doesn't explain the behaviour.

I'd expect taking address not to inject any runtime checks, especially when it's unsafeAddr.

I'd expect taking address not to inject any runtime checks, especially when it's unsafeAddr.

I agree and this will be done, but actually it never was possible. For strings it only worked because s[0] used to be no IndexError.

Isn't the problem here that we don't offer a separate call returning the starting address of the string? I don't see why the combination unsafeAddr(s[X]) should be blessed when s[X] doesn't denote a legal location. Having a starting address allows you to do any kind of pointer arithmetic yourself.

As Araq mentioned, you should use cstring as the conversion function.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

capocasa picture capocasa  路  3Comments

SolitudeSF picture SolitudeSF  路  3Comments

zaxebo1 picture zaxebo1  路  4Comments

ghost picture ghost  路  4Comments

Tronic picture Tronic  路  3Comments