2017-05-03 17:25
浏览 220


In golang, can I print the value of a memory address from a given string?

For example, if run the following code:

a := "A String"

It prints 0x1040c108.

How could I take a string such as 0x1040c108 and print the value of that string stored in the memory? Something like fmt.Println(*0x1040c108)

Is this possible?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanping3587 2017-05-03 18:29

    This can be done, but it is a really really REALLY bad idea. Anytime you are importing the unsafe package, you are either doing something wrong, or something really hardcore. I'm hesitant to even answer this, but here goes.

    package main
    import (
    func main() {
        hi := "HI"
        //address is "0x1040c128"
        var ptr uintptr = 0x1040c128
    func printPtrString(ptr uintptr) {
        p := unsafe.Pointer(ptr)

    And yes, this was pretty much taken almost line for line from the unsafe godoc.

    Also note that if/when your memory reference is NOT a go string, everything will come crashing down catastrophically.

    点赞 打赏 评论
  • dongliaoqiang8524 2017-05-03 17:30

    Yes!! you can store the address in a pointer variable and print its value by derefrencing it

    i := "something"
    ptr := &i

    For accessing the memory using a hard coded address such as 0x1040c108, it is necessary for your program to have access to that memory address otherwise, you will get an error saying invalid indirection of a pointer or segmentation fault.

    点赞 打赏 评论
  • dongmi3203 2017-05-03 18:28
    package main
    import "C"
    import (
    func main() {
        // parse the string into an integer value
        addr, _ := strconv.ParseInt("0x1040c108", 0, 64)
        // cast the integer to a c string pointer
        ptr := (*C.char)(unsafe.Pointer(uintptr(addr)))
        // convert to a go string (this will segfault)
        str := C.GoString(ptr)
        // print it
    点赞 打赏 评论