# Unsafe\_copyto! in function body problem

**URL:** <https://discourse.julialang.org/t/unsafe-copyto-in-function-body-problem/8187>\
**Category:** General Usage\
**Created:** [January 5, 2018, 6:48pm UTC](https://discourse.julialang.org/t/unsafe-copyto-in-function-body-problem/8187 "2018-01-05T18:48:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Liso](https://avatars.discourse-cdn.com/v4/letter/l/898d66/32.png) [@Liso](https://discourse.julialang.org/u/Liso)\
**Post date:** [January 5, 2018, 6:48pm UTC](https://discourse.julialang.org/t/unsafe-copyto-in-function-body-problem/8187/1 "2018-01-05T18:48:04Z")

</div>

```julia-auto
julia> function copy_bits(s::String)  
           assert(sizeof(s)>=8)
           res = UInt(0xffff) # WARNING! Don't try to use zero(UInt)! 
           p=reinterpret(Ptr{UInt8}, pointer_from_objref(res))
           unsafe_copyto!(p, pointer(s), 8)
           ntoh(res)
       end;

julia> s = "abcdefgh"
julia> copy_bits(s)
0xffff000000000000 # this is bad

```

Now I just copy paste same code and add 3 comments

```julia-auto
julia> # function copy_bits(s::String)  
         # assert(sizeof(s)>=8)
           res = UInt(0xffff) # WARNING! Don't try to use zero(UInt)! 
           p=reinterpret(Ptr{UInt8}, pointer_from_objref(res))
           unsafe_copyto!(p, pointer(s), 8)
           ntoh(res)
       # end;
0x6162636465666768 # this is good

```

#### why?

macro is working too:

```julia-auto
julia> macro copy_bits(s::String)  
           assert(sizeof(s)>=8)
           res = UInt(0xffff) # WARNING! Don't try to use zero(UInt)! 
           p=reinterpret(Ptr{UInt8}, pointer_from_objref(res))
           unsafe_copyto!(p, pointer(s), 8)
           ntoh(res)
       end
@copy_bits (macro with 1 method)

julia> @copy_bits("abcdefgh")
0x6162636465666768

```

---

<div class="post-metadata">

**Author:** ![rdeits](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rdeits/32/286_2.png) [@rdeits](https://discourse.julialang.org/u/rdeits)\
**Post date:** [January 5, 2018, 6:53pm UTC](https://discourse.julialang.org/t/unsafe-copyto-in-function-body-problem/8187/2 "2018-01-05T18:53:32Z")

</div>

I think the answer is “don’t do this”. See: [https://github.com/JuliaLang/julia/issues/15857](https://github.com/JuliaLang/julia/issues/15857) and note that this will be explicitly forbidden in Julia v0.7.

---

<div class="post-metadata">

**Author:** ![Liso](https://avatars.discourse-cdn.com/v4/letter/l/898d66/32.png) [@Liso](https://discourse.julialang.org/u/Liso)\
**Post date:** [January 5, 2018, 7:11pm UTC](https://discourse.julialang.org/t/unsafe-copyto-in-function-body-problem/8187/3 "2018-01-05T19:11:29Z")

</div>

Thanks for good hint! 🙂  
(and maybe wrong answer?)
