On Tue, May 19, 2020 at 7:53 PM Adrian Ratnapala
<[email protected]> wrote:
>
> I'd have expected that to work, because syntactically the slice is
> assigned to only after the new, smaller slice is fully constructed --
> including all the data copying.  But it still make me twitchy about
> the possibility that the runtime shortens the slice before reading all
> the data, resulting in an out-of-bounds read.
>
> As defensive programming, you can first make an explicit slice
> variable for the tail and then do the append.
>
> tail := s[i+1:]
> s = append(s[:i], tail...)
> // tail is still in scope ... so maybe that makes a differences?
>
> I'd be interested to see if this changes anything.  Because if it
> works, it smells like a bug in the runtime.

I'm really quite certain that that is not what is happening here.
This expression is a standard approach for removing an element from a
slice.  E.g., see https://golang.org/wiki/SliceTricks.

That said, it's impossible to tell what the problem is without a
complete standalone test case.

Ian




> On Wed, 20 May 2020 at 10:09, Ian Lance Taylor <[email protected]> wrote:
> >
> > On Tue, May 19, 2020 at 9:53 AM <[email protected]> wrote:
> > >
> > > I am using go-1.14.1. I am using this code to remove i-th element from 
> > > the slice.
> > >
> > > s = append(s[:i], s[i+1:]...)
> > >
> > > It works on my machine but gives panic on docker-container with error 
> > > "range out of bound" when it has just 1 element left.
> > >
> > > I want to check if this is an unsafe code and how can I improve this?
> >
> > It's hard to tell with only a code fragment.  The line you show will
> > crash if i >= len(s).
> >
> > Ian
> >
> > --
> > You received this message because you are subscribed to the Google Groups 
> > "golang-nuts" group.
> > To unsubscribe from this group and stop receiving emails from it, send an 
> > email to [email protected].
> > To view this discussion on the web visit 
> > https://groups.google.com/d/msgid/golang-nuts/CAOyqgcUdMiJLvdfYe9%2B7fzjeuwJtu6uGxmW3UE-%3D%2BZ2DQLU%3D1Q%40mail.gmail.com.
>
>
>
> --
> Adrian Ratnapala

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcXaDiJYJs8THTF7hA%2B9wqR07t31JA0eUBTTN4x1FJcmEg%40mail.gmail.com.

Reply via email to