none
Out of memory exception on StringBuilder EnsureCapacity RRS feed

  • Question

  • Hi All,

    I'm getting an out-of-memory exception on instantiation of a StringBuilder with EnsureCapacity.

           StringBuilder V_SB_mssg = new StringBuilder ();
           V_SB_mssg.EnsureCapacity((Int32.MaxValue / 2) - 2222);

    According to the docs, I should be able to set capacity to Int32.MaxValue.

    Can anyone tell me what the problem is?

    THANKS!


    Wally

    Monday, December 24, 2018 10:39 PM

All replies

  • There are multiple things to consider in case of Out of Memory like the Total Free memory at the time of allocating this amount of memory your process might already be running low on memory. For Example, 32 bit process has some limitation of how much memory it can use regardless of how much memory is installed on the machine. 

    You can read at following about those limits:

    https://blogs.msdn.microsoft.com/tom/2008/04/10/chat-question-memory-limits-for-32-bit-and-64-bit-processes/


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites


    Tuesday, December 25, 2018 4:31 AM
  • Hi Wally9633,

    Thank you for posting here.

    For your question, I test the code you provided. There is no error for me.

    Could you provide more details to reproduce the error for us to test?

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, December 25, 2018 5:25 AM
    Moderator
  • When you call StringBuilder.EnsureCapacity(), it'll call setter of StringBuilder.Capacity to the value you pass to, and therefore allocate an array of specified size. If you don't have that much continuous memory, it'll fail.

    Note that on .NET v4.0 or later, StringBuilder in .NET runtime have changed to use linked list of array instead of plain array, so if your system only has fragmented memory (i.e.: .EnsureCapacity() fails), any subsequent call to .Append() or .Insert() family of methods may still success.

    I'd say that unless you code for .NET v3.5 or before, it'd be better to just remove that call and wrap try...catch... on the call for adding data to StringBuilder. (Unless if you're initialising the StringBuilder to receive data from P/Invoke calls)


    Tuesday, January 8, 2019 7:26 AM
    Answerer