Effective time and memory for allocating memory for a string

I am reading a file in memory in C, copying bytes to a dynamic array. I am currently realloc () increasing one byte each time a new byte arrives. This seems ineffective.

Some suggest (I cannot remember where) that doubling the memory each time is more necessary because this is the output time O (log n), with a single worst-case expense of just under half the memory is not used.

Any recommendations on memory allocation?

+3
source share
3 answers

If you load the entire file into a string, you can probably use the method described in this question . This way you can get the file size in bytes and highlight your line to hold it (don't forget the extra byte for the null character).

However, if you dynamically enlarge a string, it is better to increase its size by a factor exceeding one byte (redistributing the string each byte will be very slow, especially if the string should be allocated to a new memory area and then copied). Since you are reading file doubling, this is probably very reasonable. I also saw that people use other methods, for example:

  • I saw people with the following power of 2, for example 2, 4, 8, and then 16 bytes. (which essentially doubles the file size each time).

  • , , , , .. 100 .

, .

+6

, ( , ). , . , - . Phi ( ) .

+6

, , , , , , power-of-2-resized - , ++ STL string , . ( , string::capacity .)

+2
source

Source: https://habr.com/ru/post/1773462/


All Articles