使用malloc和realloc进行动态存储的最佳方法(optimal way of using malloc and realloc for dynamic storing)

编程入门 行业动态 更新时间:2024-10-12 08:26:02
使用malloc和realloc进行动态存储的最佳方法(optimal way of using malloc and realloc for dynamic storing)

我试图弄清楚使用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.

更多推荐

本文发布于:2023-08-01 04:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1353914.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   动态   realloc   malloc   dynamic

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!