The exception is simple: you came across the situations when
asciiBytes
has the length of zero, so the index 0 is invalid. The valid range is just empty, no index can be used. You simply should check that the current length of
asciiBytes
is greater than zero, before doing the indexing in the last line you show.
The fragment of code shown cannot cause the memory leaks. When you do
gcnew
, the object is created, and Garbage Collector (GC) takes care about reclaiming the memory, when the object becomes
unreachable (more exactly, at some later moment of time which you cannot really control). Please read to learn the basic ideas of
garbage collection and the role of
reachability:
http://en.wikipedia.org/wiki/Garbage_collection_%28computer_science%29[
^].
However, don't think that the leak of managed memory is not possible. I quite possible, but not as a result of some random bugs, but more typically due to mistakes in general design of the code. I explain this matter in my past answers. Please see:
Garbage collectotion takes care of all the memory management[
^],
deferring varirable inside the loop can cuase memory leak?[
^],
Best way to get rid of a public static List Causing an Out of Memory[
^],
Memory management in MDI forms[
^].
Such memory leaks are much less likely, but if you have such kind of a leak, it's harder to figure out. You will need to analyze your code design. I hope my explanations will help you to do that.
—SA