# Problem with memcpy, marshal, zero

**URL:** <https://www.ruby-forum.com/t/problem-with-memcpy-marshal-zero/103381>\
**Category:** Ruby\
**Created:** [May 4, 2007, 10:20pm UTC](https://www.ruby-forum.com/t/problem-with-memcpy-marshal-zero/103381 "2007-05-04T22:20:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![danielb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c57346/32.png) [@danielb](https://www.ruby-forum.com/u/danielb)\
**Post date:** [May 4, 2007, 10:20pm UTC](https://www.ruby-forum.com/t/problem-with-memcpy-marshal-zero/103381/1 "2007-05-04T22:20:48Z")

</div>

Hi,

Ruby 1.8.6  
Windows XP Pro

In the win32-mmap package I have the code setup such that you can  
create a dynamic accessor. Internally, I marshal the value (as a hash)  
and copy it to an address via memcpy (wrapped using Win32API). So,  
when you do something like this:

mm = MMap.new(:size =\> 12, :name =\> ‘test’)  
mm.gvalue = 5  
p mm.gvalue # 5  
mm.close

It’s actually doing something like this when you set a value:

h = {“gvalue”=\>0}  
m = Marshal.dump(h)  
p m =\> “\004\b{\006”\vgvaluei\000"  
memcpy(address, marshal, marshal.length)

The problem is that trailing “\000” gets chopped off by the memcpy  
function because it treats it like a trailing null as far as I can  
tell. So, when I try to load it again the marshal data isn’t  
identical, i.e. the trailing “\000” is gone, and I end up getting a  
“marshal data too short” error.

What’s the solution here?

Thanks,

Dan

---

<div class="post-metadata">

**Author:** ![danielb](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c57346/32.png) [@danielb](https://www.ruby-forum.com/u/danielb)\
**Post date:** [May 5, 2007, 6:05pm UTC](https://www.ruby-forum.com/t/problem-with-memcpy-marshal-zero/103381/2 "2007-05-05T18:05:05Z")

</div>

- Daniel B. (removed\_email\_address@domain.invalid) wrote:

> What’s the solution here?

At the end of Win32API\_Call() I see:

```
case _T_POINTER:
        return rb_str_new2((char *)ret);

```

rb\_str\_new2 does rb\_str\_new(ptr, strlen(ptr)), so if you’re using  
Win32API to return any string with a NULL byte, it’ll get truncated. On  
the other hand, I’ve not spotted anything wrt input to suggest NULL is  
handled as a delimiter; are you sure the NULL isn’t being copied  
properly, but not being returned properly by another call?
