Hi,
On 31/7/21 11:20, aitor wrote:
> On 31/7/21 3:02, Bruce Perens via Dng wrote:
>> If you want this, it's easy enough to allocate your own stack, and
>> write functions that allocate from it and release the allocation.
>
> Sometimes I use the following buffer struct for dynamic allocation:
>
> https://gitea.devuan.dev/aitor_czr/libnetaid/src/branch/master/backend_src/sbuf.c
> <https://gitea.devuan.dev/aitor_czr/libnetaid/src/branch/master/backend_src/sbuf.c>
>
> A tiny version of the one developed by Johan Malm (bunsenlabs):
>
> https://github.com/johanmalm/jgmenu/blob/master/src/sbuf.c
> <https://github.com/johanmalm/jgmenu/blob/master/src/sbuf.c>
>
> I added a variadic function enabling the concatenation of several strings:
>
> sbuf_concat(&buffer, N, string1, string2, ..., stringN);
>
I added a new feature to the sbuf struct using the *cleanup* common
variable attribute [*] which runs automatically the function:
void free_buf(struct sbuf *s)
{
free(s->buf);
}
when the variable goes out of the scope.
You can test this behavior (the complete example is here:
https://www.gnuinos.org/sbuf/ <
https://www.gnuinos.org/sbuf/>) running
the following program:
#include <stdio.h>
#include "sbuf.h"
int main(int argc, char **argv)
{
struct sbuf s __cleanbuf__(free_buf);
sbuf_init(&s);
sbuf_addstr(&s, "oo");
return 0;
}
When the memory is deallocated, the program will print:
Cleaning up->"oo"
Cheers,
Aitor.
[*]
https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html#Common-Variable-Attributes
<
https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html#Common-Variable-Attributes>