The best way to use malloc and realloc for dynamic storage

I'm trying to figure out what is the best way to use malloc and realloc to get an unknown number of characters from the user, store and print them only to the end.

I realized that calling realloc too many times would not be so smart. so instead, I allocate a given amount of space each time, say sizeof char * 100, and by the end of the file I use realloc to fit exactly the size of everything.

Do you think this is a good way? will you go the other way?

Please note: I am not going to use linked lists, getchar (), putchar (). the use of malloc and realloc is required.

+4
source share
2 answers

, . , , , 1) realloc 2) , . , - , .

, " " , , realloc :

, , . size_t mempool_size = n * _Alignof(int); , , , n, 8.

, , mempool_size*2 . , .

+3

, realloc .

? - .

, , , . getchar(), , , realloc(), char , . realloc() , . , glibc malloc(), , 16 . 0 16 . , , . , , realloc() , .

. , , , , , . . , , ( realloc()), . . , , . 256 , , , . 4Kb .

, . , . , Java - , , , , Cocoa .

, . , , , , , . , .

, , - . , , , , . OpenSSL.

0

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


All Articles