PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How the underlying array behaves in 'slice' in Golang

 May 13, 2022     append, arrays, go, memory-management, slice     No comments   

Issue

I am quite confused about the array in a slice. Code is posted below.

I understand test() takes a copy of arr from main(), and the 'append' in test() doesn't allocate a new array because cap > len.

However, it seems that the underlying array in the test slice arr[] and main slice arr[] are different, since their addresses are different.

On the other hand, the 'append' operation in test() does modify the underlying array in the main(), because a new '1' appears when the underlying array of the main slice gets printed. Also, test() is able to set arr[0] = 10, which is visible in main().

How does this happen?

The address of array in slice is taken from this post.

func test(arr []int) {
    arr[0] = 10
    fmt.Printf("test slice - %p \n", &arr) //
    hdr := (*reflect.SliceHeader)(unsafe.Pointer(&arr))
    data := *(*[10]int)(unsafe.Pointer(hdr.Data))
    fmt.Printf("test - %p \n", &data)
    arr = append(arr, 1)
    fmt.Printf("test slice = %p \n", &arr) //
    hdr = (*reflect.SliceHeader)(unsafe.Pointer(&arr))
    data = *(*[10]int)(unsafe.Pointer(hdr.Data))
    fmt.Printf("test = %p \n", &data)
}

func main() {
    var arr []int = make([]int, 4, 10)
    hdr := (*reflect.SliceHeader)(unsafe.Pointer(&arr))
    data := *(*[10]int)(unsafe.Pointer(hdr.Data))
    fmt.Printf("main - %p \n", &data)
    test(arr)
    hdr = (*reflect.SliceHeader)(unsafe.Pointer(&arr))
    data = *(*[10]int)(unsafe.Pointer(hdr.Data))
    fmt.Printf("main = %p \n", &data)
    fmt.Println("main data ", data)
}

Output:

main - 0xc00009e050 
test slice - 0xc0000a6000 
test - 0xc00009e0a0 
test slice = 0xc0000a6000 
test = 0xc00009e0a0 
main = 0xc00009e050 
main data  [10 0 0 0 1 0 0 0 0 0]

Solution

This operation:

    data := *(*[10]int)(unsafe.Pointer(hdr.Data))

copies the [10]int array into data. Here, data is a new array, not the backing array of the slice.



Answered By - Burak Serdar
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing