ubyte[] to string with @nogc - different behaviors
Adam D. Ruppe
destructionator at gmail.com
Wed Aug 5 18:25:37 UTC 2020
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...)
You mnight be best off just doing plain
return cast(string) bytes_ptr[0 .. len].idup;
as the whole function.
> 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.
More information about the Digitalmars-d
mailing list