我正在嘗試在 Go 中進行實驗,看看如果我在堆棧上存儲一個指向變量的指針,然后在原始變量離開作用域后訪問該變量會發生什么。package mainimport "fmt"var p chan bool;// a temp structtype v struct { a int}func another_thread(vx *v) { // this code should be executed after a() returns so vx should be a pointer to a value that's no longer on the stack fmt.Printf("another_thread(): %p\n", vx); vx.a = 4 // am I updating a dangling pointer that may have unintentional side effects?? fmt.Println(" - ", vx.a); p<-true;}func update_v(vx *v) { vx.a = 3; fmt.Printf("update_v(): %p\n", vx); go another_thread(vx)}func alloc_on_stack() { // allocate v1 on the stack var v1 v v1.a = 1 fmt.Printf("alloc_on_stack(): %p\n", &v1); // pass a pointer to v1 on the stack update_v(&v1) // print '3' to prove byref actually took it by reference fmt.Println(" - ", v1.a); // when the function returns, v1 should be popped off the stack}func main() { p = make(chan bool) alloc_on_stack(); fmt.Println("outside of alloc_on_stack, waiting"); <-p; fmt.Println("done");}在 alloc_on_stack 中,v1 作為局部變量存儲在堆棧上。我將指向 v1 的指針傳遞給 update_v,后者將其傳遞給 another_thread。由 another_thread 直到 alloc_on_stack 完成后才執行。然而,當我運行該代碼時,我沒有收到任何錯誤,而是看到了以下內容:alloc_on_stack(): 0x1043617cupdate_v(): 0x1043617c - 3outside of alloc_on_stack, waitinganother_thread(): 0x1043617c - 4doneanother_thread 中的 vx 不應該是一個懸空指針嗎?
存儲指向堆棧值的指針(Golang)
慕尼黑5688855
2021-09-13 16:28:28