ubyte[] to string with @nogc - different behaviors

Luhrel lucien.perregaux at gmail.com
Wed Aug 5 18:51:40 UTC 2020


On Wednesday, 5 August 2020 at 18:25:37 UTC, Adam D. Ruppe wrote:
> On Wednesday, 5 August 2020 at 18:17:15 UTC, Luhrel wrote:
>> string toString(const(ubyte)* bytes_ptr, size_t len) @nogc
>> {
>>     const(ubyte)[] bytes = bytes_ptr[0 .. len];
>>     char* str_ptr = cast(char*)malloc(len * ubyte.sizeof);
>>     string str = cast(string)str_ptr[0 .. len];
>>     str = cast(string)bytes[];
>
> You just leaked str_ptr there. It gets overwritten by bytes' 
> ptr.
> I imagine what you meant to do was
>
> str_ptr[0 .. len] = bytes_ptr[0 .. len];
> string str = cast(string)str_ptr[0 .. len];
> return str;
>
> or something like that instead to copy the data over. (Though 
> note this is still liable to leak since the user has no 
> indication they need to free it...)

Thanks, that's what I was looking for.

> You mnight be best off just doing plain
>
> return cast(string) bytes_ptr[0 .. len].idup;
>
> as the whole function.
>

Unfortunately, this uses the GC.

>
>
>>         char* str_ptr = cast(char*)malloc(bytes.length() * 
>> ubyte.sizeof);
>>         string str = cast(string)str_ptr[0 .. bytes.length()];
>>         str = cast(string)bytes[];
>
> but since you again leak the new memory and just refer back to 
> the old, it is liable to be overwritten once the function 
> exists.

Ooooooh I see now.
The different behavior is due to `read!ubyte` which removes the 
byte from the buffer, that's why I can't simply write `return 
cast(string)bytes[];`.



More information about the Digitalmars-d mailing list