I am writing the implementation of the "eternal buffer", the question arose of which operation is more expensive than malloc or realloc .
The first implementation option:
- When initializing the buffer, memory is allocated using
malloc, for what they want to write to it:buff* a = buff_init("data", 4), something like this. - When writing with
reallocexpand the allocated buffer and write data.
The second implementation:
- During initialization, a block is created with a valid size of 1kb, and a pointer to the next block (default is
NULL). - If the block is filled, a new one is allocated, updating the pointers in the previous one (without using
realloc)
This implies a number of questions, please help:
- How expensive is it to use the
reallocoperation compared tomalloc? - How does
reallocwork? - How does
freedetermine the end of the memory to be freed? - What is the optimal block size to choose for 2 variants of implementation?
- How is the
stringclass implemented in C ++, is it also a kind of perpetual buffer?
What to read about it? Thank!