| Thread overview | |||||
|---|---|---|---|---|---|
|
November 14, 2022 Why am I getting different array size depending where I calling? | ||||
|---|---|---|---|---|
| ||||
Hi all,
Well my doubt is pretty much the title for the snippet below:
import std.stdio;
void[] getFoo(){
void[] _ = new void[int.sizeof*2];
(cast(int[])_)[0] = 2;
return _;
}
void main() {
void[] bar = new void[int.sizeof*2];
(cast(int[])bar)[0] = 1;
writeln(cast(int[])bar);
auto foo = getFoo();
writeln(foo);
return;
}
Prints:
[1, 0]
[2, 0, 0, 0, 0, 0, 0, 0]
Looking through godbolt.org the ASM generated with both
void[] bar = new void[int.sizeof*2];
or
void[] _ = new void[int.sizeof*2];
is the same:
mov rdi, qword ptr [rip + TypeInfo_Av.__init@GOTPCREL]
mov esi, 8
call _d_newarrayT@PLT
mov qword ptr [rbp - 16], 8
mov qword ptr [rbp - 8], rdx
So why the array generated from getFoo() is 4 times bigger than the other?
Thanks in advance,
Matheus.
| ||||
November 14, 2022 Re: Why am I getting different array size depending where I calling? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to matheus | On Monday, 14 November 2022 at 21:00:38 UTC, matheus wrote:
> void[] getFoo(){
> writeln(cast(int[])bar);
> auto foo = getFoo();
> writeln(foo);
>
> Prints:
>
> [1, 0]
> [2, 0, 0, 0, 0, 0, 0, 0]
>
> Looking through godbolt.org the ASM generated with both
>
> So why the array generated from getFoo() is 4 times bigger than the other?
It isn't. You're casting one to int[] and not casting the other, leaving it as void[], which writeln will interpret as just raw bytes.
Since an int is 4x bigger than a byte, casting it to int shows 1/4 the number of ints.
But the actual array is the same.
| |||
November 14, 2022 Re: Why am I getting different array size depending where I calling? | ||||
|---|---|---|---|---|
| ||||
Posted in reply to Adam D Ruppe | On Monday, 14 November 2022 at 21:07:42 UTC, Adam D Ruppe wrote:
> On Monday, 14 November 2022 at 21:00:38 UTC, matheus wrote:
>> void[] getFoo(){
>> writeln(cast(int[])bar);
>> auto foo = getFoo();
>> writeln(foo);
>>
>> Prints:
>>
>> [1, 0]
>> [2, 0, 0, 0, 0, 0, 0, 0]
>>
>> Looking through godbolt.org the ASM generated with both
>>
>> So why the array generated from getFoo() is 4 times bigger than the other?
>
> It isn't. You're casting one to int[] and not casting the other, leaving it as void[], which writeln will interpret as just raw bytes.
>
> Since an int is 4x bigger than a byte, casting it to int shows 1/4 the number of ints.
>
> But the actual array is the same.
Oh my, you're absolutely right... I can't believe I missed that.
Thanks Adam,
Matheus.
| |||
Copyright © 1999-2021 by the D Language Foundation
Permalink
Reply