note that if you intend to return said values, then it is not valid to
return things on the stack.
partial reason:
there is nothing to say that the stack wont expand again and randomly thrash
your data.
now, what I do:
I narrow the problem to things where I would have to use a heap (of some
sort, I often implement customized memory managers, which are often garbage
collectors), and where one can get by with purely temporary memory.
in this latter case (the memory is only temporary, but should probably last
at least until I am done with it...), I tend to implement what I call a
"rotating allocator".
basically:
I allocate some chunk of memory (say, 64KiB, 256KiB, or 1MiB, for good
measure);
I retain a pointer into the chunk of memory;
as I allocate, I slide along this pointer, and if an allocation would cross
the end, the pointer is reset back to the start again (no allocations are
remembered, so I simply overwrite any old data...).
usually, I try to keep the number of such allocators small, in order to
avoid using too much extra memory...
I often use this kind of setup for temporary strings, string buffers, and
similar. if the data needs any real 'permanence', I transfer it to an actual
heap.
or such...
- Show quoted text -- Hide quoted text -
- Show quoted text -
I understand what you mean, but let me explain what I'm doing...
I'm implementing a String class and, of course, I provide some
functions to create and manipulate it:
GekkotaString* gekkota_string_new();
....
int32_t gekkota_string_append(GekkotaString *string, const
GekkotaString *value);
int32_t gekkota_string_insert(GekkotaString *string, const
GekkotaString *value, int32_t index);
....
The first parameter always refers the object being manipulated, while
the second parameter is the value to append, insert, and so on. As you
can see, the second parameter is also a pointer to a String object,
but I want to be able to specify also a const character string without
having to create an extra String object. Let me provide an example:
/* Pedantic way */
GekkotaString *s1 = gekkota_string_new("Hello");
GekkotaString *s2 = gekkota_string_new(", World");
gekkota_string_append(s1, s2); /* The value of s1 is now "Hello,
World" */
/* easy way */
GekkotaString *s1 = gekkota_string_new("Hello");
gekkota_string_append(s1, _str(", World")); /* The value of s1 is now
"Hello, World" */
Function _str() just does the trick we discussed yesterday.
Of course, I could have defined a second variant of the append()
function like this:
int32_t gekkota_string_append_1(GekkotaString *string, const char_t
*value);
but that's less elegant in my opinion.
That's it.
j3d.