A safer interface for core.stdc
Andrei Alexandrescu via Digitalmars-d
digitalmars-d at puremagic.com
Sat Feb 7 18:19:19 PST 2015
On 2/7/15 5:26 PM, H. S. Teoh via Digitalmars-d wrote:
> On Sun, Feb 08, 2015 at 12:39:39AM +0000, bearophile via Digitalmars-d wrote:
>> Andrei Alexandrescu:
>>
>>> Such wrappers would allow safe code to use more C stdlib primitives.
>>
>> I'd also like a safer templated wrapper for calloc() and malloc() and
>> similar.
> [...]
>
> You mean something like this?
>
> T* malloc(T)() @trusted
> {
> return cast(T*)malloc(T.sizeof);
> }
I think that would go as follows:
private @system T[] mallocUninitializedArrayImpl(T)(size_t n)
{
auto p = malloc(n * T.sizeof);
p || assert(0, "Not enough memory");
return (cast(T*) p)[0 .. n];
}
@trusted T[] mallocUninitializedArray(size_t n)
if (!hasIndirections!T)
{
return mallocUninitializedArrayImpl!T(n);
}
@system T[] mallocUninitializedArray(size_t n)
if (hasIndirections!T)
{
return mallocUninitializedArrayImpl!T(n);
}
Similarly there'd be a mallocMinimallyInitializedArray that zeroes only
pointers and is @trusted for all types.
Then we'd probably have a @trusted callocArray that blasts zeros
throughout. It's @trusted because we know pointers are zeroes (an
assumption somewhat not robust in theory but fine in practice).
Then we'd have a mallocArray that allocates an array and initializes
each element with .init.
> struct MyStruct {
> int x, y, z;
> }
>
> void main() {
> auto p = malloc!MyStruct();
>
> // Not sure how to make free() usable from @safe, unless
> // we wrap the pointer returned by malloc().
> free(p);
> }
Indeed we have no safe way to wrap free.
Andrei
More information about the Digitalmars-d
mailing list