Is this a bug?

I came across an issue like this over the last few days when playing with some windows api’s but the issue also happens on the mac. I put a little demo together that I used to diagnose the issue and ultimately work around it.

If you put this code into a new project on window1.open and run it, why does the program crash or you get random garbage in s when trying to populate s ?

Dim w As WString = "Hello" Dim mb As MemoryBlock = w + chr(0) 'ensure the string is null terminated so wstring is happy Dim p As Ptr = mb 'create a pointer to the memoryblock Break 'at this break, you can see the string in the IDE variable viewer via the pointer without issue Dim s As String = p.WString(0) 'as soon as you do this the program crashes Break

Is this a bug in the framework, should this result in something other than a crash or corruption?

Cheers

Oh, just in case you are interested, here’s the workaround

Dim w As WString = "Hello" Dim mb As MemoryBlock = w + chr(0) 'ensure the string is null terminated so wstring is happy Dim p As Ptr = mb Break 'at this break, you can see the string in the IDE variable viewer without issue Dim mb2 As MemoryBlock = p 'THIS IS THE WORKAROUND and change the following line to mb2.WString(0) Dim s As String = mb2.WString(0) 'as soon as you do this the program crashes Break

I’d report it as a bug
Seems odd you have to put the ptr into a memoryblock to access things that way

When you ask ptr for a String at offset zero, it will look on the bytes and use them as ptr.
But “Hell” will not be a valid ptr value!

This must crash and is not a bug as far as I see.
If you use ptr, you must know what they point to.

I don’t understand what you’re saying Christian. Why do you mention “Hell”, the string is “Hello”

I also know what they point to, I just made the WString and pointed at that?

In memoryblock, wstring and cstring both set/get a string in the memory addressed by the memoryblock. (inline)

In ptr, wstring and cstring are handling offset as an address pointing to another address that contains a cstring/wstring.

The following works:

Dim w As wString = "Hello"
Dim mb As new MemoryBlock(8)
dim mb2 as MemoryBlock= w+chr(0) 
mb.ptr(0)=mb2 'mb now has the pointer to the wstring  (not the wstring itself)
Dim p As Ptr = mb 'create a pointer to the memoryblock
Dim s As String = p.WString(0) 'now you're getting the wstring at the address pointed to at the 0 offset
Break

[quote=450397:@Christian Schmitz]When you ask ptr for a String at offset zero, it will look on the bytes and use them as ptr.
But “Hell” will not be a valid ptr value![/quote]

Ahhh it’s finally clicked, I see what you’re alluding to here, thanks!

Of course, a WString is actually stored as a pointer to a string!

Thanks all, yes reading random memory isn’t really something the framework can handle, nor me being daft!