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:

  1. 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.
  2. When writing with realloc expand the allocated buffer and write data.

The second implementation:

  1. During initialization, a block is created with a valid size of 1kb, and a pointer to the next block (default is NULL ).
  2. 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:

  1. How expensive is it to use the realloc operation compared to malloc ?
  2. How does realloc work?
  3. How does free determine the end of the memory to be freed?
  4. What is the optimal block size to choose for 2 variants of implementation?
  5. How is the string class implemented in C ++, is it also a kind of perpetual buffer?

What to read about it? Thank!

    1 answer 1

    1. malloc less expensive than realloc , since in the case of malloc finds and selects a section of free memory of the required size, and the location of this section is not so important.
    2. When using realloc , the malloc operation is performed, and then the previously allocated part of bytes is copied.
    3. malloc when allocating memory, records meta information, these are already memory management issues. In general, these functions are just wrappers for invoking OS kernel operations.
    4. Depends on the data, the size may be dynamic. In general, look towards the data structures, in this case you almost described the list.
    5. Generally it is an array of characters. You can find implementations .
    • Thanks, one more question, calloc is the same malloc that multiplies its inputs, how does it work? - Another ghost account ...
    • multiplies? He just scores all the allocated memory with zeros - Komdosh
    • @Komdosh multiplies each byte by zero :) - αλεχολυτ
    • @Komdosh It means that calloc two arguments, and the total size is obtained by multiplying them, apparently. - HolyBlackCat
    • @HolyBlackCat yes, that is what it meant. I did not know that calloc wipes zeros. Thank you very much! - Another ghost account ...