B
Bob Eaton
I need to allocate a buffer to be used with some non-managed code to do text
processing. Until now, I'd been using "stackalloc" in order to avoid
fragmenting the memory too much as a result of using "new", but recently,
someone gave me a very long string to process and the following code threw
the System.StackOverflowException:
int nBufSize = sInput.Length * 10;
byte* lpInBuffer = stackalloc byte [ nBufSize ];
I tried to put try...catch around this, but it can't catch the exception
(presumably because the stack is already clobbered by that point).
Anyway, in order to accomodate a large buffer situation, I'd like to do
something like say, "if the requested size is larger than the amount of
space on the stack, then use 'new' instead."
First of all, is "the amount of space on the stack" even determinable at
run-time? If not, I don't mind hard-coding something like, 100000 (or some
such value), but I can't get it to compile...
I've tried to change it to something like this:
const int cnMaxStackSize = 100000;
byte* lpInBuffer = (nBufSize > cnMaxStackSize) ? stackalloc
byte[nBufSize] : new byte[nBufSize];
But that doesn't work because "stackalloc is only valid in local variable
initializers."
Is there anything I can do besides simply using 'new' instead?
Thanks,
Bob
processing. Until now, I'd been using "stackalloc" in order to avoid
fragmenting the memory too much as a result of using "new", but recently,
someone gave me a very long string to process and the following code threw
the System.StackOverflowException:
int nBufSize = sInput.Length * 10;
byte* lpInBuffer = stackalloc byte [ nBufSize ];
I tried to put try...catch around this, but it can't catch the exception
(presumably because the stack is already clobbered by that point).
Anyway, in order to accomodate a large buffer situation, I'd like to do
something like say, "if the requested size is larger than the amount of
space on the stack, then use 'new' instead."
First of all, is "the amount of space on the stack" even determinable at
run-time? If not, I don't mind hard-coding something like, 100000 (or some
such value), but I can't get it to compile...
I've tried to change it to something like this:
const int cnMaxStackSize = 100000;
byte* lpInBuffer = (nBufSize > cnMaxStackSize) ? stackalloc
byte[nBufSize] : new byte[nBufSize];
But that doesn't work because "stackalloc is only valid in local variable
initializers."
Is there anything I can do besides simply using 'new' instead?
Thanks,
Bob