-4

In a loop, I am adding one million strings (mostly 2 to 3 characters long) to a List<string>. At the end of every iteration, the string list is cleared. Most of the iterations go on without trouble. But at one particular iteration, the string list throws OutOfMemoryException even with only 700,000 string elements in it. I have no idea why this happens and how to resolve it. Can anyone help?

Steven Ackley
  • 593
  • 7
  • 31
Navaneeth
  • 102
  • 9

2 Answers2

1

Since you havent provided any code for people to see, it will be difficult to identify, however this is the cause(s) of OutOfMemoryException:

Details from MSDN.

  • You are attempting to expand a StringBuilder object beyond the length defined by its StringBuilder.MaxCapacity property.

  • The common language runtime cannot allocate enough contiguous memory to successfully perform an operation. This exception can be thrown by any property assignment or method call that requires a memory allocation.

For more information on the cause of the OutOfMemoryException exception, see https://blogs.msdn.microsoft.com/ericlippert/2009/06/08/out-of-memory-does-not-refer-to-physical-memory/.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

This should be far less than the theoretical maximum size for a list. However, the List class uses an array as the underlying store, so it stores everything in contiguous memory locations. If your memory is highly fragmented it's possible that there aren't enough contiguous memory locations.