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.8k stars 2.17k forks source link

Mutable access to an immutable array trough mutable slice #17435

Open veranovus opened 1 year ago

veranovus commented 1 year ago

Describe the bug

You can mutate an immutable array if you access it trough a mutable slice, its a fairly simple bug to reproduce.

Code:

module main

fn main() {
    nums := []int{len: 5, init: it}

    mut slice := nums[1..3]

    slice[0] = 12

    println('N, S: ${nums}, ${slice}')
}

Expected Behavior

This code either should not have worked at all or slice should've copied array data and changed that.

Current Behavior

Data of the immutable array changes.

Reproduction Steps

  1. Create an immutable array
  2. Create a mutable slice using that array
  3. Change a value in the slice

Code Example:

module main

fn main() {
    nums := []int{len: 5, init: it}

    mut slice := nums[1..3]

    slice[0] = 12

    println('N, S: ${nums}, ${slice}')
}

Possible Solution

I dunno, compiler should check it? Maybe? No Idea

Additional Information/Context

No response

V version

V 0.3.3 b7b6c23

Environment details (OS name and version, etc.)

OS: macos, macOS, 13.2, 22D49 Processor: 8 cpus, 64bit, little endian, Apple M1 CC version: Apple clang version 14.0.0 (clang-1400.0.29.202)

felipensp commented 1 year ago

@medvednikov what should be approach to fix this one? checker error? automatic cloning?

medvednikov commented 1 year ago

@felipensp a checker error and allow modifying it, like Go does.

I don't think we should do cloning here. What do you think @spytheman