Forum > General

[SOLVED] Trying to allocate memory on the heap without exceptions/runtime errors

(1/2) > >>

furious programming:
I don't need it, but I'm curious. Is it possible in Free Pascal to allocate a block of data on the heap and get a pointer to it, but if there is any problem with the allocation, then no exception and runtime error will be emitted? If the block cannot be allocated, the result should be a nil pointer, nothing more. Example of use:


--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---  function TryGetMem(ASize: PtrUInt): Pointer;  begin    // Some implementation, no support of runtime errors and exceptions.    // Just return "nil" of the block cannot be allocated.  end; var  Block: Pointer;begin  // Try to allocate a block of memory on the heap and get pointer to it.  Block := TryGetMem(4096);   // Test if the memory block was allocated successfully.  if Block <> nil then  begin    // Memory is allocated, so use it.     FreeMem(Block);  end  else    // The block was not allocated, so handle this situation yourself.
Can something like this be done or does a runtime error or exception always have to be emitted?

paweld:

--- Code: Pascal  [+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i < x.length; i++) { x[i].style.maxHeight='none'; x[i].style.height = Math.min(x[i].clientHeight+15,306)+'px'; x[i].style.resize = "vertical";}};} ---function TryGetMem(ASize: PtrUInt): Pointer;begin  ReturnNilIfGrowHeapfails := True; //add this  GetMem(Result, ASize);  end; 
https://www.freepascal.org/docs-html/rtl/system/getmem.html and https://www.freepascal.org/docs-html/rtl/system/returnnilifgrowheapfails.html

furious programming:
Ah, it is so easy. Thank you very much your answear.  8)

jamie:
isn't that what the TRY ... Except .... END is for?

furious programming:

--- Quote from: jamie on December 03, 2022, 03:26:00 pm ---isn't that what the TRY ... Except .... END is for?
--- End quote ---

It doesn't matter — I wanted to know if it is possible to avoid runtime errors and exceptions.

Navigation

[0] Message Index

[#] Next page

Go to full version