0

Is there any other way to keeping getting console input from the user and store it?

Arun
  • 45
  • 1
  • 5

2 Answers2

2

Well, you can of course pre-allocate some "large" buffer and use parts of it as needed, that will save you from having to use heap memory.

That does mean that there will be a static (=known in advance) limit though; the only away around that is by using heap through malloc() and realloc().

unwind
  • 391,730
  • 64
  • 469
  • 606
0

No. There are three different memory allocation devices in C: malloc, calloc, and realloc. Compared to the other two, realloc is very, very expensive since every time you call realloc it re-initializes the entire memory bank (for this reason it's better to initialize in powers of 2: 1, 2, 4, 8, 16, 32 so that the copy process doesn't take as long as if you just initialized one additional variable location at a time).

The major difference in how malloc and calloc act is that malloc does not initialize the memory, so you could end up with literally any garbage in there while calloc will set the memory to '0' all the way down.

ciphermagi
  • 747
  • 3
  • 14
  • I don't think that's true about realloc. In the implementations I know it's either free, very cheap, or exactly the same cost as one malloc(), one free() and one memcpy(). – david.pfx Mar 03 '14 at 09:37
  • It's not. The cost is immense. Remember that memcpy() has a HUGE cost of its own that increases on an exponential curve as the length of memory to be copied increases. – ciphermagi Mar 03 '14 at 09:43
  • Please think first. A realloc of the same or smaller size is usually free; a realloc of slightly larger involves a small book-keeping task; and memcpy is O(n) not O(n^2). See also http://stackoverflow.com/questions/362760/how-do-realloc-and-memcpy-work. – david.pfx Mar 03 '14 at 10:07
  • david, try this sometime. I've done it, and I have data on it that would prove that realloc is much more expensive: Run 100,000,000,000 mallocs Run 100,000,000,000 reallocs See which one takes longer. – ciphermagi Mar 03 '14 at 10:14
  • @cipermagi: I have and I know the result: I can produce any answer you want by changing the parameters ever so slightly. I can cripple your computer with less than 100 mallocs, and I can run a billion reallocs in no more than a few seconds. I suggest you go read some source code to find out how this stuff really works. I just checked the MSVC 2012 RTL and it does just what I remember. – david.pfx Mar 03 '14 at 10:41
  • No, it doesn't. NO memory operation is free. – ciphermagi Mar 03 '14 at 10:42