Deutsch English Français Italiano |
<86tt7uqo2u.fsf@linuxsc.com> View for Bookmarking (what is this?) Look up another Usenet article |
Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch <tr.17687@z991.linuxsc.com> Newsgroups: comp.lang.c Subject: Re: What is your opinion about init_malloc? Date: Sat, 15 Mar 2025 09:02:33 -0700 Organization: A noiseless patient Spider Lines: 41 Message-ID: <86tt7uqo2u.fsf@linuxsc.com> References: <vr1e67$1fa1p$1@dont-email.me> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Date: Sat, 15 Mar 2025 17:02:34 +0100 (CET) Injection-Info: dont-email.me; posting-host="3e46727b472ba2d5903adccba45d2adf"; logging-data="3913750"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19Q1uhLrJbBagMkNYvgfW0utq0YzrelfMY=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:A8pbmjMj/e1quV82fnXMWA/O9RM= sha1:FBB4DccX2/Y/3R8QKnkdm35MIvM= Bytes: 2085 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.