vlang / v

Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. Supports automatic C => V translation. https://vlang.io
MIT License
35.68k stars 2.15k forks source link

segfault for simple program #14911

Closed wtholliday closed 10 months ago

wtholliday commented 2 years ago

V version: V 0.3.0 f0cee25 OS: macOS 12.4 (21F79)

What did you do?

Compiled and ran the following program:

struct Node {
    val   int
    left  &Node
    right &Node
}

fn main() {
    n := Node { 123, 0, 0 }
    m := *n.left
    println(m)
}

using:

./v test.v
./test

What did you expect to see?

Runtime error for null de-reference, or compiler error disallowing initialization of reference to null.

What did you see instead?

./test
signal 11: segmentation fault
0   libsystem_platform.dylib            0x00007ff81638adfd _sigtramp + 29
1   ???                                 0x7867a93a2954f3b8 0x0 + 8676089274419180472
2   test                                0x000000010bd160d7 main + 71
3   test                                0x000000010bcefa04 start + 52
Wertzui123 commented 2 years ago

I think this is intended behavior and not a bug, but maybe it should be changed.

JalonSolov commented 2 years ago

It's never intended to get a segfault. Not sure how this one can be caught, since it's a runtime failure.

Wertzui123 commented 2 years ago

I guess there would have to be a wrapper around dereferencing that checks if the reference is valid.

andersk commented 2 years ago

If you plan to keep advertising “No null” on the home page, that implies the language should guarantee that safe code cannot even produce a null reference, like in Rust or Haskell. Achieving that guarantee requires careful language design (see also #10837 for maps, #14911 for arrays). But if you have that guarantee, checks on dereferencing should not be needed.

In this case, initializing &Node with 0 should be forbidden. A tree-like structure should use an optional type ?&Node for fields that may or may not point to a Node. It looks like other fixes may be necessary to support that usage.

medvednikov commented 2 years ago

It is forbidden, it requires unsafe. This particular issue is a bug where the unsafe check is not enforced.

damywise commented 1 year ago

Just some info: This is now a RUNTIME ERROR: invalid memory access https://vosca.dev/p/2276f28ae1

andersk commented 1 year ago

@damywise That is how the V playground displays a segfault. Nothing’s changed.

damywise commented 1 year ago

Ah I see, I misunderstood then. Sorry about that