mobiruby/mruby-cfunc — pull request #25 by schmurfy (2013-06-03 09:40:28+00:00)
Title: Pointer size not enforced

This is not really a pull request, more like an issue with a failing test as a start.
The problem is really simple, here is the failing test:

```ruby
ptr2 = CFunc::UInt8[4]
CFunc::call(CFunc::Void, "strcpy", ptr2, "too long")
assert_equal "too ", ptr2.to_s
```

For me the problem is in the following code:

```c
mrb_value
cfunc_pointer_to_s(mrb_state *mrb, mrb_value self)
{
struct cfunc_type_data *data = DATA_PTR(self);
size_t len;
mrb_value str;
struct RString *s;
const char* p = (const char*)get_cfunc_pointer_data(data);

len = strlen(p); // <-- problem

str = mrb_str_new(mrb, 0, len);
s = mrb_str_ptr(str);
strcpy(s->ptr, p);
s->len = strlen(s->ptr);
return str;
}
```

When calling to_s on a pointer an strlen is done to check the string size, this is both wrong and dangerous and a good example of the reason why strncpy even exist...

While I know where the problem is I don't know what is the proper way to fix it, I think the pointer should store its allocated memory space and not try to go beyond its boundaries, in C if I did what the failing test does I would expect a segmentation fault but in this case I suppose the allocated memory space is inside a buffer reserved by mruby core and so instead of a segmentation fault this would just overwrite memory associated to another object/extension.

I noticed this problem when doing some tests with string arrays in structures.