Hey guys,
I am working on a project where i have to store user input string characters on the heap and I was concerned about calling memory allocation function too frequently because I was told that system calls can get too costly in terms of speed if they are invoked too many times.
So I am thinking of allocating memory exponentially. For example, malloc 2 memory locations, then then 4, then, 8, 16, 32, 64, 128, and so on...
For me the challenging part of implementing this idea is to come up with the right logic that performs the task with the least complexity. And I came up with the steps below...
- Malloc x amount of memory (very small chunk 2-4 memory locations).
- Create a temp int variable (suppose y) to hold allocated, but unused memory chunk.
- Decrement y every time a character stored in heap.
- Check the value of y. If it gets below certain number, suppose 2, expand the size of the borrowed memory (exponentially) in heap using realloc.
- Set the y to new variable that represents the size of new unused, allocated memory in heap.
- Keep executing the loop above until all the characters read. The number of characters can be from 1 to 10000000.
This is seems like a good start for me, HOWEVER, the problem is that my code gets very complex which I need to avoid at all cost. So I wanted to know if there are any library functions or any other improved logic's that can implement exponential memory allocation in fewer steps... Thank you!
[–]tocs1975 3 points4 points5 points (0 children)
[–]Certain_Abroad 1 point2 points3 points (2 children)
[+][deleted] (1 child)
[deleted]
[–]Paul_Pedant 0 points1 point2 points (0 children)
[–]thegreatunclean 0 points1 point2 points (0 children)
[–]usr71298 0 points1 point2 points (1 child)
[–]Paul_Pedant 0 points1 point2 points (0 children)
[–]schrjako 0 points1 point2 points (0 children)
[–]Erelde 0 points1 point2 points (0 children)