Sujet : Re: What is your opinion about init_malloc?
De : tr.17687 (at) *nospam* z991.linuxsc.com (Tim Rentsch)
Groupes : comp.lang.cDate : 15. Mar 2025, 17:02:33
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <86tt7uqo2u.fsf@linuxsc.com>
References : 1
User-Agent : Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Thiago Adams <
thiago.adams@gmail.com> writes:
What is your opinion about init_malloc?
One problem it solves it to initialise a const objects on heap.
>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
>
void * init_malloc(size_t size, void * src)
{
void * p = malloc(size);
if (p) {
memcpy(p, src, size );
}
return p;
}
>
#define ALLOC(OBJ) ((typeof(OBJ)*) init_malloc(sizeof(OBJ), &(OBJ)))
>
////////// SAMPLE //////////
>
struct Mail {
const int id;
};
>
int main () {
struct Mail* p0 = ALLOC((struct Mail){.id= 1});
>
struct Mail* p1 = init_malloc(sizeof *p1, &(struct Mail){.id= 1});
>
auto p2 = ALLOC((struct Mail){.id= 1});
>
}
Some facility along these lines looks like it would be useful, but
in terms of what is shown here the implementation is ugly and the
interface is poorly chosen. For starters the initializing function
should be for internal use only, so all client use is through some
higher-level macro interface. Also the interface name ALLOC is a
terrible choice.