Nim: Casting a pointer to an UncheckedArray[uint8] crashes the compiler

Created on 5 May 2019  路  3Comments  路  Source: nim-lang/Nim

When you cast[UncheckedArray[uint8]], the compiler doesn't report an error, it just crashes.

Example

var
  rawMem = alloc0(20)
  byteUA = cast[UncheckedArray[uint8]](rawMem)

byteUA[3] = 12'u8
echo byteUA[4]

Current Output

Error: internal error: genAssignment: tyUncheckedArray
No stack traceback available
To create a stacktrace, rerun compilation with ./koch temp c <file>

Expected Output

The compiler should report that you need to cast to a ptr UncheckedArray[uint8], not UncheckedArray[uint8]

Additional Information

$ nim -v
Nim Compiler Version 0.19.9 [Linux: amd64]
Compiled at 2019-05-02
Copyright (c) 2006-2019 by Andreas Rumpf

active boot switches: -d:release

related issue: #9403

Crash Error messages

Most helpful comment

Crash aside, this is the correct solution:

var
  rawMem = alloc0(20)
  byteUA = cast[ptr UncheckedArray[uint8]](rawMem)

byteUA[3] = 12'u8
echo byteUA[4]

Arrays are not pointers in Nim. Never.

All 3 comments

Casting unchecked array has worked for me (example). I'll try out your example tomorrow to understand what's different between the 2 cases. I am just allocating the exact array size using sizeof, whereas you are allocating using an int literal.

Crash aside, this is the correct solution:

var
  rawMem = alloc0(20)
  byteUA = cast[ptr UncheckedArray[uint8]](rawMem)

byteUA[3] = 12'u8
echo byteUA[4]

Arrays are not pointers in Nim. Never.

Ah yes, I missed that I am using cast[ptr .. in my example :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

SolitudeSF picture SolitudeSF  路  3Comments

juancarlospaco picture juancarlospaco  路  3Comments

capocasa picture capocasa  路  3Comments

kobi2187 picture kobi2187  路  4Comments

Vindaar picture Vindaar  路  3Comments