我试图弄清楚使用malloc和realloc从用户那里收集未知数量的字符,存储它们以及仅在结束时打印它们的最佳方法。
我认为调用realloc太多次都不会那么聪明。 所以相反,我每次都分配一定量的空间,让我们说sizeof char * 100和文件的结尾,我使用realloc来精确地拟合整个事物的大小。
你觉得怎么样?这是一个很好的方式吗? 你会走另一条路吗?
请注意,我无意使用链表,getchar(),putchar()。 仅使用malloc和realloc是必须的。
I'm trying to figure out what is the optimal way of using malloc and realloc for recieving unknown amount of characters from the user ,storing them, and printing them only by the end.
I've figured that calling realloc too many times wont be so smart. so instead, I allocate a set amount of space each time,lets say sizeof char*100 and by the end of file,i use realloc to fit the size of the whole thing precisely.
what do you think?is this a good way to go about? would you go in a different path?
Please note,I have no intention of using linked lists,getchar(),putchar(). using malloc and realloc only is a must.
最满意答案
如果重新分配以适应所需的确切数据量,那么您将优化内存消耗。 这可能会导致代码变慢,因为1)您获得了额外的realloc调用; 2)您可能无法分配适合CPU对齐和数据缓存的数量。 可能这也会导致堆分段问题,因为重复的reallocs,在这种情况下它实际上可能浪费内存。
通常很难回答什么是“最佳”,但下面的方法相当常见,因为它是降低realloc调用的执行速度和降低内存使用之间的良好折衷:
您分配一个段,然后跟踪该段是用户数据的多少。 分配size_t mempool_size = n * _Alignof(int);是个好主意size_t mempool_size = n * _Alignof(int); 使用可被8整除的n也可能是明智的。
每次在此段中耗尽可用内存时,都会重新分配到mempool_size*2个字节。 这样你每次都可以将可用内存增加一倍。
If you realloc to fit the exact amount of data needed, then you are optimizing for memory consumption. This will likely give slower code because 1) you get extra realloc calls and 2) you might not allocate amounts that fit well with CPU alignment and data cache. Possibly this also causes heap segmentation issues because of the repeated reallocs, in which case it could actually waste memory.
It's hard to answer what's "best" generically, but the below method is fairly common, as it is a good compromise between reducing execution speed for realloc calls and lowering memory use:
You allocate a segment, then keep track of how much of this segment that is user data. It is a good idea to allocate size_t mempool_size = n * _Alignof(int); bytes and it is probably also wise to use a n which is divisible by 8.
Each time you run out of free memory in this segment, you realloc to mempool_size*2 bytes. That way you keep doubling the available memory each time.
更多推荐
发布评论