Danny
Danny

Reputation: 141

problem with buffer of byte long much 1MB

as i can solve this problem: i want use a buffer of byte of 1 MB or more, with array it not is possible becouse i have a stack overlflow. I have thinked about getmem and freemem, or using tmemorystream, but not have understood exactely as solve it. To me need for use a buffer for copy a file using tfilestream with read/write. I don't want load all fine in one time in memory and after write it in disk all in time too; for it, i have found solution, but not need me it. Thanks very much. Daniela.

Upvotes: 2

Views: 1029

Answers (3)

Premature Optimization
Premature Optimization

Reputation: 1938

Your buffer variable is allocated on stack and default maximum stack size used by Delphi compiler is 1 MiB. So the solution is to set higher limit by using project options or the following global directive:

{$MAXSTACKSIZE 4194304} // eg. now maximum is 4 MiB 

Other way is to use heap instead of stack, any of dynamically allocated memory, in your case probably best solution will be a dynamic array.

Performance note: stack is faster than heap.

Upvotes: 0

CodesInChaos
CodesInChaos

Reputation: 108810

One easy solution is using a dynamic array. Their data is allocated on the heap, so you will avoid the stackoverflow. The advantage of them over directly working with memory allocation functions is that they are refcounted and the memory they allocated will automatically be freed once the last reference goes out of scope.

var buffer:array of byte;
begin
  SetLength(buffer,100000);
  ...
  //Will be freed here as buffer goes out of scope
end;

Upvotes: 2

David Heffernan
David Heffernan

Reputation: 612993

If you have a stack overflow then your variable doesn't fit on the stack. You are clearly using a local variable.

Solve the problem by using the heap instead. Either GetMem or SetLength.

Upvotes: 3

Related Questions