Looks like dereferencing a null pointer, but is ok???
Regan Heath
regan at netwin.co.nz
Mon Sep 11 18:25:36 PDT 2006
On Mon, 11 Sep 2006 16:41:52 -0700, Sean Kelly <sean at f4.ca> wrote:
> Regan Heath wrote:
>> On Mon, 11 Sep 2006 14:12:20 -0700, Sean Kelly <sean at f4.ca> wrote:
>>> Georg Wrede wrote:
>>>> In an old message,
>>>>
>>>>>> I don't think that any extra overhead is involved in slicing. D
>>>>>> doesn't even check if a pointer is valid.
>>>>>> (That might be a gotcha come to think of it)
>>>>>>
>>>>>> void main()
>>>>>> {
>>>>>> char[] foo = (cast(char*)null)[0..10];
>>>>>> }
>>>>>
>>>>> Great example! I am now convinced there is nothing
>>>>>> to worry about. Thanks everyone for the help!
>>>> I'm baffled.
>>>> I would have expected this to cause an error!
>>>> And if really not, what in the world is
>>>> (cast(char*)null)[0..10]
>>>> supposed to mean, or return???
>>>
>>> Who knows what it means--it should cause an access violation at run
>>> time.
>> Why? I mean null is the memory address 0x0 and slicing simply assigns
>> a string to the values given, eg.
>> //assuming
>> struct string {
>> void* data;
>> int length;
>> }
>> //we get
>> string a;
>> a.data = null;
>> a.length = 10;
>
> Oh true. I forgot that the slice syntax doesn't actually dereference
> the memory if the slice occurs on an rvalue. So I suppose it would be
> okay. But you obviously couldn't do anything with the slice.
True. In fact the slice is toxic, doing anything with it is likely to
cause a crash. It's possible that creating an array by slicing a null
pointer will occur often enough that adding a special check for that case
will prevent a number of bugs.
Regan
More information about the Digitalmars-d-learn
mailing list