### FastMM_GetInstallationState Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/memory-manager-installation.md Returns the current installation state of FastMM. ```APIDOC ## FastMM_GetInstallationState ### Description Returns the current installation state of FastMM. ### Returns `TFastMM_MemoryManagerInstallationState` — One of: - `mmisDefaultMemoryManagerInUse` — Default memory manager is in use - `mmisOtherThirdPartyMemoryManagerInstalled` — Another third-party manager is installed - `mmisUsingSharedMemoryManager` — Using a shared memory manager - `mmisInstalled` — FastMM5 is installed ### Example ```pascal var State: TFastMM_MemoryManagerInstallationState; begin State := FastMM_GetInstallationState; case State of mmisDefaultMemoryManagerInUse: WriteLn('Default memory manager in use'); mmisOtherThirdPartyMemoryManagerInstalled: WriteLn('Another third-party manager installed'); mmisUsingSharedMemoryManager: WriteLn('Using shared memory manager'); mmisInstalled: WriteLn('FastMM5 is installed'); end; end; ``` ``` -------------------------------- ### Memory Manager Installation Functions Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/INDEX.md Functions for installing and managing the FastMM5 memory manager. ```APIDOC ## FastMM_AttemptToUseSharedMemoryManager() ### Description Attempts to use a shared memory manager instance. ### Method Call ## FastMM_ShareMemoryManager() ### Description Makes the current memory manager instance available for sharing. ### Method Call ## FastMM_Initialize() ### Description Manually initializes the FastMM5 memory manager. ### Method Call ## FastMM_Finalize() ### Description Manually finalizes the FastMM5 memory manager. ### Method Call ## FastMM_GetInstallationState() ### Description Retrieves the current installation status of the memory manager. ### Method Call ### Returns The installation state. ``` -------------------------------- ### Catching Cannot Install After Default Memory Manager Used Error Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/errors.md This snippet demonstrates how to detect if FastMM cannot be installed because the default memory manager has already been used. Ensure FastMM is the first unit in your project's DPR file to avoid this. ```pascal if not FastMM_Initialize then WriteLn('FastMM could not be installed - default manager already used'); ``` -------------------------------- ### Add FastMM5 to Project Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/00_START_HERE.md Include FastMM5.pas as the first unit in your DPR file to automatically install it with optimized defaults. ```pascal program MyApp; uses FastMM5, // Must be first! Forms, MainForm in 'MainForm.pas'; begin Application.Initialize; Application.CreateForm(TMainForm, MainForm); Application.Run; end. ``` -------------------------------- ### Get FastMM Installation State Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/memory-manager-installation.md Returns the current installation state of FastMM. The state indicates whether the default manager is in use, another third-party manager is installed, a shared manager is being used, or FastMM5 is installed. ```pascal function FastMM_GetInstallationState: TFastMM_MemoryManagerInstallationState; ``` ```pascal var State: TFastMM_MemoryManagerInstallationState; begin State := FastMM_GetInstallationState; case State of mmisDefaultMemoryManagerInUse: WriteLn('Default memory manager in use'); mmisOtherThirdPartyMemoryManagerInstalled: WriteLn('Another third-party manager installed'); mmisUsingSharedMemoryManager: WriteLn('Using shared memory manager'); mmisInstalled: WriteLn('FastMM5 is installed'); end; end; ``` -------------------------------- ### Manager Installation Functions Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/README.md Functions for installing and uninstalling the FastMM memory manager. ```APIDOC ## FastMM_Initialize() ### Description Install FastMM (manual mode). ### Method Call ### Parameters None explicitly documented. ### Response None. ``` ```APIDOC ## FastMM_Finalize() ### Description Uninstall FastMM (manual mode). ### Method Call ### Parameters None explicitly documented. ### Response None. ``` ```APIDOC ## FastMM_GetInstallationState() ### Description Get current installation state. ### Method Call ### Parameters None explicitly documented. ### Response Current installation state of FastMM. ``` ```APIDOC ## FastMM_AttemptToUseSharedMemoryManager() ### Description Switch to shared manager. ### Method Call ### Parameters None explicitly documented. ### Response Boolean indicating success. ``` ```APIDOC ## FastMM_ShareMemoryManager() ### Description Start sharing this manager. ### Method Call ### Parameters None explicitly documented. ### Response None. ``` -------------------------------- ### TFastMM_MemoryManagerInstallationState Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/types.md Indicates the current installation state of the memory manager, reflecting its active status and configuration. ```APIDOC ## Enumeration: TFastMM_MemoryManagerInstallationState ### Description Indicates the current installation state of the memory manager. ### Values - **mmisDefaultMemoryManagerInUse**: Default memory manager is in use. - **mmisOtherThirdPartyMemoryManagerInstalled**: Another third-party manager is installed. - **mmisUsingSharedMemoryManager**: Using shared manager from another module. - **mmisInstalled**: FastMM5 is installed and active. ### Used By `FastMM_GetInstallationState()` ``` -------------------------------- ### Use a Different Debug Library Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/configuration.md Example of changing the debug support library by assigning a new DLL name to FastMM_DebugSupportLibraryName before entering debug mode. ```pascal // Use a different debug library FastMM_DebugSupportLibraryName := PWideChar('MyDebugLibrary.dll'); FastMM_EnterDebugMode; ``` -------------------------------- ### Initialize FastMM Memory Manager Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/memory-manager-installation.md Initializes and installs FastMM as the memory manager. This function is called automatically during unit initialization unless FastMM_DisableAutomaticInstall is defined. When that define is used, this function must be called from application code very early. Returns true if FastMM was successfully installed. ```pascal function FastMM_Initialize: Boolean; ``` ```pascal begin // Manual initialization (only if FastMM_DisableAutomaticInstall is defined) if FastMM_Initialize then WriteLn('FastMM initialized and installed') else WriteLn('FastMM could not be installed'); end; ``` -------------------------------- ### Allocate Memory Top-Down Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/configuration.md Example of setting FastMM_AllocateTopDown to True to enable top-down memory allocation. This can improve error detection for pointer typecasts in 64-bit applications. ```pascal // Allocate from top-down for better error detection FastMM_AllocateTopDown := True; ``` -------------------------------- ### TFastMM_MemoryManagerInstallationState Enum Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/types.md Indicates the current installation state of the memory manager. Used by FastMM_GetInstallationState(). ```pascal type TFastMM_MemoryManagerInstallationState = ( mmisDefaultMemoryManagerInUse, mmisOtherThirdPartyMemoryManagerInstalled, mmisUsingSharedMemoryManager, mmisInstalled ); ``` -------------------------------- ### Install FastMM5 in Delphi Project Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/README.md Add FastMM5.pas as the first unit in your project's DPR file to integrate it as the default memory manager. ```pascal program MyApp; uses FastMM5, // Must be first Forms, MainForm in 'MainForm.pas'; begin Application.Initialize; Application.CreateForm(TMainForm, MainForm); Application.Run; end. ``` -------------------------------- ### Dumping FastMM5 Memory State to a Log File Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/errors.md Provides an example of how to dump the detailed memory state of FastMM5 to a specified log file before application exit. This is useful for viewing details of detected memory leaks. ```pascal // Before exit, dump detailed state to log FastMM_LogStateToFile(PWideChar('C:\Logs\Memory.log')); ``` -------------------------------- ### Catching Another Third-Party Memory Manager Installed Error Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/errors.md Use this code to check if another memory manager is installed before attempting to install FastMM. This prevents conflicts and ensures proper initialization. ```pascal if FastMM_GetInstallationState <> mmisInstalled then begin if FastMM_GetInstallationState = mmisOtherThirdPartyMemoryManagerInstalled then WriteLn('Another memory manager is already installed'); end; ``` -------------------------------- ### Get Current Event Log Filename Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/event-logging.md Retrieves the current full path and filename used for the event log. ```pascal function FastMM_GetEventLogFilename: PWideChar; var LogFile: PWideChar; begin LogFile := FastMM_GetEventLogFilename; WriteLn(Format('Event log file: %s', [LogFile])); end; ``` -------------------------------- ### Get Memory Map Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/state-logging.md Gets the state of every 64K block in the lower 4GB of the address space. Useful for analyzing address space usage, especially under 32-bit systems. ```Pascal procedure FastMM_GetMemoryMap( var AMemoryMap: TMemoryMap; ALockTimeoutMilliseconds: Cardinal = 50 ); ``` ```Pascal var MemMap: TMemoryMap; begin FastMM_GetMemoryMap(MemMap); // Process the memory map to analyze address space usage WriteLn('Memory map retrieved'); end; ``` -------------------------------- ### Enable Corruption Scan Before Every Operation Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/configuration.md Example of enabling the corruption scan for every memory operation by setting FastMM_DebugMode_ScanForCorruptionBeforeEveryOperation to True. This has a significant performance impact. ```pascal FastMM_EnterDebugMode; FastMM_DebugMode_ScanForCorruptionBeforeEveryOperation := True; // Now every operation scans for corruption (very slow) ``` -------------------------------- ### Assign Custom Stack Trace Routine Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/configuration.md Example of assigning a custom stack trace routine to FastMM_GetStackTrace before entering debug mode. This allows for custom call stack capture logic. ```pascal // Assign custom stack trace routine FastMM_GetStackTrace := MyCustomStackTraceProc; FastMM_EnterDebugMode; // Now debug mode uses your custom routine ``` -------------------------------- ### FastMM_Initialize Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/memory-manager-installation.md Initializes and installs FastMM as the memory manager. This function is called automatically during unit initialization unless `FastMM_DisableAutomaticInstall` is defined. When that define is used, this function must be called from application code very early, before the default memory manager has been used. ```APIDOC ## FastMM_Initialize ### Description Initializes and installs FastMM as the memory manager. This function is called automatically during unit initialization unless `FastMM_DisableAutomaticInstall` is defined. When that define is used, this function must be called from application code very early, before the default memory manager has been used. ### Returns `Boolean` — True if FastMM was successfully installed. False if another memory manager is already installed or the default memory manager has already been used. ### Example ```pascal begin // Manual initialization (only if FastMM_DisableAutomaticInstall is defined) if FastMM_Initialize then WriteLn('FastMM initialized and installed') else WriteLn('FastMM could not be installed'); end; ``` ``` -------------------------------- ### Get Memory Usage Summary Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/00_START_HERE.md Retrieve and display the total allocated memory bytes used by the application. The result is converted to megabytes for readability. ```pascal var Summary := FastMM_GetUsageSummary; WriteLn(Format('Used: %.2f MB', [Summary.AllocatedBytes / 1024 / 1024])); ``` -------------------------------- ### Memory Limits Functions Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/README.md Functions for setting and getting memory usage limits. ```APIDOC ## FastMM_SetMemoryUsageLimit() ### Description Set maximum allocation limit. ### Method Call ### Parameters - **Limit** (Integer) - The maximum memory usage limit in bytes. ### Response None. ``` ```APIDOC ## FastMM_GetMemoryUsageLimit() ### Description Get current limit. ### Method Call ### Parameters None explicitly documented. ### Response Current memory usage limit in bytes. ``` -------------------------------- ### Keep FastMM Active After Unit Finalization Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/configuration.md Example of setting FastMM_NeverUninstall to True to prevent FastMM from being uninstalled during unit finalization. This is useful when pointers must remain valid. ```pascal // Keep FastMM active even after unit finalization FastMM_NeverUninstall := True; ``` -------------------------------- ### Enter FastMM Debug Mode Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/debug-mode.md Enters debug mode, enabling extra metadata logging and error checking. Debug mode can be nested. Returns false if the memory manager is not installed or has changed. Note the significant performance penalty and increased memory usage. ```pascal function FastMM_EnterDebugMode: Boolean; ``` ```pascal begin if FastMM_EnterDebugMode then try WriteLn('Debug mode entered'); var P := FastMM_GetMem(256); // Block now has debug metadata including stack traces and checksums FastMM_FreeMem(P); finally FastMM_ExitDebugMode; end else WriteLn('Failed to enter debug mode'); end; ``` -------------------------------- ### FastMM_EnterDebugMode Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/debug-mode.md Enters debug mode, which can be nested. Debug mode remains active as long as `FastMM_EnterDebugMode` calls exceed `FastMM_ExitDebugMode` calls. In this mode, extra metadata is logged, and additional checks are performed to catch common programming errors. Returns true on success, or false if the memory manager instance is not installed or has changed. ```APIDOC ## FastMM_EnterDebugMode ### Description Enters debug mode. Calls may be nested; debug mode remains active as long as the number of `FastMM_EnterDebugMode` calls exceeds `FastMM_ExitDebugMode` calls. In debug mode, extra metadata is logged before and after user data, and additional checks catch common programming errors. ### Return Type `Boolean` — True on success. False if this memory manager instance is not currently installed or the installed memory manager has changed. ### Throws None. ### Note Debug mode comes with significant performance penalty. All blocks allocated in debug mode use more address space due to extra metadata. ### Example ```pascal begin if FastMM_EnterDebugMode then try WriteLn('Debug mode entered'); var P := FastMM_GetMem(256); // Block now has debug metadata including stack traces and checksums FastMM_FreeMem(P); finally FastMM_ExitDebugMode; end else WriteLn('Failed to enter debug mode'); end; ``` ``` -------------------------------- ### Manual FastMM5 Initialization Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/INTEGRATION_GUIDE.md Use this pattern for custom startup logic, allowing manual control over FastMM5 initialization and finalization. Ensure FastMM_Initialize returns true before proceeding. ```pascal program MyApp; uses FastMM5; {$define FastMM_DisableAutomaticInstall} procedure Initialize; begin if not FastMM_Initialize then begin ShowMessage('Failed to initialize FastMM'); Halt(1); end; WriteLn('FastMM5 initialized'); end; procedure Finalize; begin if FastMM_Finalize then WriteLn('FastMM5 finalized') else WriteLn('FastMM was not the active memory manager'); end; begin try Initialize; try // Application code finally Finalize; end; except on E: Exception do WriteLn('Fatal error: ' + E.Message); end; end. ``` -------------------------------- ### Basic Memory Allocation and Freeing Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/README.md Demonstrates how to allocate and free memory using FastMM_GetMem and FastMM_FreeMem. Ensure memory is freed in a finally block to prevent leaks. ```pascal var P: Pointer; begin // Allocate memory P := FastMM_GetMem(1024); if P <> nil then begin try // Use memory finally // Free memory FastMM_FreeMem(P); end; end; end; ``` -------------------------------- ### Configure FastMM5 Behavior with Conditional Defines Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/INTEGRATION_GUIDE.md Add these defines to your project's .dpr file or compiler options before the unit keyword to control FastMM5's startup behavior. ```pascal {$define FastMM_FullDebugMode} // Start in debug mode {$define FastMM_EnableMemoryLeakReporting} // Report leaks at shutdown {$define FastMM_Align16Bytes} // 16-byte alignment {$define FastMM_ShareMM} // Share memory manager {$define FastMM_6Arenas} // 6 arenas for threading ``` -------------------------------- ### Load FastMM Debug Support Library Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/debug-mode.md Attempts to load the debug support library. Sets stack trace handlers if not already customized. Returns true on success or if already loaded. ```pascal function FastMM_LoadDebugSupportLibrary: Boolean; ``` ```pascal begin // Attempt to load debug support library if FastMM_LoadDebugSupportLibrary then WriteLn('Debug support library loaded') else WriteLn('Debug support library not available'); end; ``` -------------------------------- ### Set Optimization Strategy (Runtime) Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/INDEX.md Configure the memory manager's optimization strategy at runtime using a function call. Options include mmosBalanced (default), mmosOptimizeForSpeed, and mmosOptimizeForLowMemoryUsage. ```pascal FastMM_SetOptimizationStrategy(mmosBalanced) ``` -------------------------------- ### Implement Custom Stack Tracing with FastMM5 Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/INTEGRATION_GUIDE.md Allows you to provide custom routines for capturing and formatting stack traces, useful for integrating with third-party debugging tools. ```pascal procedure MyGetStackTrace( APReturnAddresses: PNativeUInt; AMaxDepth, ASkipFrames: Cardinal); begin // Implement your own stack trace capture // For example, using EurekaLog, MadExcept, or custom logic WriteLn(Format('Capturing %d stack frames', [AMaxDepth])); // Fill APReturnAddresses with return addresses end; function MyConvertStackTraceToText( APReturnAddresses: PNativeUInt; AMaxDepth: Cardinal; APBuffer, APBufferEnd: PWideChar): PWideChar; begin // Implement your own stack trace formatting WriteLn('Converting stack trace to text'); Result := APBuffer; // Format and copy text to buffer end; procedure SetupCustomStackTracing; begin FastMM_GetStackTrace := MyGetStackTrace; FastMM_ConvertStackTraceToText := MyConvertStackTraceToText; FastMM_EnterDebugMode; // Now debug mode uses your custom routines WriteLn('Custom stack tracing enabled'); end; ``` -------------------------------- ### FastMM_GetMemoryMap Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/state-logging.md Gets the state of every 64K block in the lower 4GB of the address space (covers entire address space under 32-bit). ```APIDOC ## FastMM_GetMemoryMap ### Description Gets the state of every 64K block in the lower 4GB of the address space (covers entire address space under 32-bit). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None (Procedure Call) ### Endpoint None (Procedure Call) ### Parameters - **AMemoryMap** (TMemoryMap) - Required - Output variable receiving the memory map. - **ALockTimeoutMilliseconds** (Cardinal) - Optional - 50 - Max wait time for arena locks. ### Request Example ```pascal var MemMap: TMemoryMap; begin FastMM_GetMemoryMap(MemMap); // Process the memory map to analyze address space usage end; ``` ### Response #### Success Response None (Output parameter AMemoryMap is populated) #### Response Example None ``` -------------------------------- ### FastMM_LoadDebugSupportLibrary Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/debug-mode.md Attempts to load the debug support library. If successful, it sets the stack trace handlers to routines within the library, unless custom handlers are already in place. Returns true if the library was loaded successfully or was already loaded, and false if loading failed. ```APIDOC ## FastMM_LoadDebugSupportLibrary ### Description Attempts to load the debug support library (FastMM_FullDebugMode.dll or FastMM_FullDebugMode64.dll). On success, sets the FastMM_GetStackTrace and FastMM_ConvertStackTraceToText handlers to routines in the library, unless custom handlers have already been assigned. ### Return Type `Boolean` — True if the library was loaded successfully or was already loaded. False if loading failed. ### Throws None. ### Example ```pascal begin // Attempt to load debug support library if FastMM_LoadDebugSupportLibrary then WriteLn('Debug support library loaded') else WriteLn('Debug support library not available'); end; ``` ``` -------------------------------- ### Get FastMM5 Memory Usage Summary Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/README.md Retrieves a summary of memory usage, including allocated bytes and efficiency percentage, using FastMM_GetUsageSummary. ```pascal var Summary: TFastMM_UsageSummary; begin Summary := FastMM_GetUsageSummary; WriteLn(Format('Allocated: %d MB', [Summary.AllocatedBytes div 1024 div 1024])); WriteLn(Format('Efficiency: %.1f%%', [Summary.EfficiencyPercentage])); end; ``` -------------------------------- ### Enter and Exit Debug Mode (Pascal) Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/errors.md Use FastMM_EnterDebugMode and FastMM_ExitDebugMode to bracket application code for error detection. Configure stack trace depth with FastMM_SetDebugModeStackTraceEntryCount. ```pascal procedure DetectMemoryErrors; begin FastMM_EnterDebugMode; try // Application code here - errors will be caught FastMM_SetDebugModeStackTraceEntryCount(16); // Full stack traces // Run your tests finally FastMM_ExitDebugMode; end; end; ``` -------------------------------- ### Analyze Memory Usage with FastMM5 Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/README.md This Pascal program demonstrates how to retrieve and display memory usage statistics and manager state using FastMM5 functions. It logs the detailed memory state to a file. ```pascal program MemoryAnalysis; uses FastMM5; procedure AnalyzeMemory; var Summary: TFastMM_UsageSummary; State: TFastMM_MemoryManagerState; begin Summary := FastMM_GetUsageSummary; FastMM_GetMemoryManagerState(State); WriteLn('Memory Analysis:'); WriteLn(Format(' Allocated: %.2f MB', [Summary.AllocatedBytes / 1024 / 1024])); WriteLn(Format(' Overhead: %.2f MB', [Summary.OverheadBytes / 1024 / 1024])); WriteLn(Format(' Efficiency: %.1f%%', [Summary.EfficiencyPercentage])); WriteLn(Format(' Small blocks: %d types', [State.SmallBlockTypeCount])); WriteLn(Format(' Medium blocks: %d', [State.AllocatedMediumBlockCount])); WriteLn(Format(' Large blocks: %d', [State.AllocatedLargeBlockCount])); end; begin AnalyzeMemory; // Log detailed state FastMM_LogStateToFile(PWideChar('C:\Logs\memory_state.log')); WriteLn('Memory state logged to file'); end. ``` -------------------------------- ### Get Current FastMM Optimization Strategy Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/optimization-configuration.md Retrieves the currently active optimization strategy of the memory manager. This can be used to check the current configuration. ```Pascal function FastMM_GetCurrentOptimizationStrategy: TFastMM_MemoryManagerOptimizationStrategy; var Strategy: TFastMM_MemoryManagerOptimizationStrategy; begin Strategy := FastMM_GetCurrentOptimizationStrategy; case Strategy of mmosOptimizeForSpeed: WriteLn('Currently optimized for speed'); mmosBalanced: WriteLn('Currently balanced'); mmosOptimizeForLowMemoryUsage: WriteLn('Currently optimized for low memory usage'); end; end; ``` -------------------------------- ### Get Current Minimum Address Alignment Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/optimization-configuration.md Retrieves the current effective minimum address alignment. If multiple alignment requests are active, it returns the coarsest one. ```pascal function FastMM_GetCurrentMinimumAddressAlignment: TFastMM_MinimumAddressAlignment; ``` ```pascal var CurrentAlignment: TFastMM_MinimumAddressAlignment; begin CurrentAlignment := FastMM_GetCurrentMinimumAddressAlignment; case CurrentAlignment of maa8Bytes: WriteLn('8-byte alignment'); maa16Bytes: WriteLn('16-byte alignment'); maa32Bytes: WriteLn('32-byte alignment'); maa64Bytes: WriteLn('64-byte alignment'); end; end; ``` -------------------------------- ### Enter Minimum Address Alignment (Pascal) Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/optimization-configuration.md Requests that all subsequent allocated blocks be aligned to a specified minimum. Useful for SIMD operations or other alignment-sensitive code. Calls may be nested; coarser alignment requests have precedence. ```pascal procedure FastMM_EnterMinimumAddressAlignment(AMinimumAddressAlignment: TFastMM_MinimumAddressAlignment); ``` ```pascal var P1, P2, P3: Pointer; begin // Request 16-byte alignment for SIMD operations FastMM_EnterMinimumAddressAlignment(maa16Bytes); try P1 := FastMM_GetMem(256); // Will be 16-byte aligned P2 := FastMM_GetMem(512); // Will be 16-byte aligned finally FastMM_ExitMinimumAddressAlignment(maa16Bytes); end; // Back to default alignment P3 := FastMM_GetMem(128); FastMM_FreeMem(P1); FastMM_FreeMem(P2); FastMM_FreeMem(P3); end; ``` -------------------------------- ### Attempt to Use Shared Memory Manager Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/memory-manager-installation.md Searches the current process for a shared memory manager. Use this to switch to a shared manager if this instance has not yet allocated memory. Returns true if switching succeeded or if this instance is already the shared manager. ```pascal function FastMM_AttemptToUseSharedMemoryManager: Boolean; ``` ```pascal begin // Try to use a memory manager shared by another module if FastMM_AttemptToUseSharedMemoryManager then WriteLn('Using shared memory manager from another module') else WriteLn('Could not switch to shared manager or this is the shared manager'); end; ``` -------------------------------- ### Get Current Memory Usage Limit Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/optimization-configuration.md Retrieves the current memory usage limit. Returns 0 if no limit is set. Use this to check the configured memory ceiling. ```pascal function FastMM_GetMemoryUsageLimit: NativeUInt; begin Limit := FastMM_GetMemoryUsageLimit; if Limit = 0 then WriteLn('No memory limit set') else WriteLn(Format('Memory limited to %.2f MB', [Limit / 1024 / 1024])); end; ``` -------------------------------- ### Enable Full Debug Mode (Compile-time) Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/INDEX.md Use this conditional define during compilation to enable full metadata tracking, automatic stack trace capture, and corruption detection. ```pascal {$define FastMM_FullDebugMode} ``` -------------------------------- ### Get Debug Mode Stack Trace Entry Count Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/debug-mode.md Returns the current depth of allocation and free stack traces in debug mode. The value ranges from 0 to CFastMM_MaximumStackTraceEntryCount. ```pascal function FastMM_GetDebugModeStackTraceEntryCount: Byte; var Depth: Byte; begin Depth := FastMM_GetDebugModeStackTraceEntryCount; WriteLn(Format('Current stack trace depth: %d', [Depth])); end; ``` -------------------------------- ### Memory Allocation Functions Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/README.md Functions for basic memory allocation, deallocation, and resizing. ```APIDOC ## FastMM_GetMem() ### Description Allocate memory block. ### Method Call ### Parameters None explicitly documented. ### Response Memory block pointer. ``` ```APIDOC ## FastMM_FreeMem() ### Description Free memory block. ### Method Call ### Parameters - **Ptr** (Pointer) - The memory block to free. ### Response None. ``` ```APIDOC ## FastMM_ReallocMem() ### Description Resize memory block. ### Method Call ### Parameters - **Ptr** (Pointer) - The memory block to resize. - **NewSize** (Integer) - The new size for the memory block. ### Response Pointer to the resized memory block. ``` ```APIDOC ## FastMM_AllocMem() ### Description Allocate zero-initialized memory. ### Method Call ### Parameters - **Size** (Integer) - The size of the memory block to allocate. ### Response Pointer to the zero-initialized memory block. ``` -------------------------------- ### Get Registered Memory Leaks Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/expected-memory-leaks.md Retrieves a dynamic array containing records of all currently registered expected memory leaks. Use this to iterate and inspect details of each registered leak. ```Pascal function FastMM_GetRegisteredMemoryLeaks: TFastMM_RegisteredMemoryLeaks; begin // Implementation omitted for brevity end; ``` ```Pascal var Leaks: TFastMM_RegisteredMemoryLeaks; I: Integer; begin Leaks := FastMM_GetRegisteredMemoryLeaks; for I := 0 to High(Leaks) do begin WriteLn(Format('Leak %d: Address=%p, Size=%d, Count=%d', [I, Leaks[I].LeakAddress, Leaks[I].LeakSize, Leaks[I].LeakCount])); end; end; ``` -------------------------------- ### Allocate and Zero-Initialize Memory - FastMM_AllocMem Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/core-memory-management.md FastMM_AllocMem allocates memory and initializes all bytes to zero. This is useful for structures that require zero-initialization upon allocation. Remember to free the memory with FastMM_FreeMem. ```pascal function FastMM_AllocMem(ASize: NativeInt): Pointer; ``` ```pascal type TMyRecord = record A: Integer; B: string; end; var P: ^TMyRecord; begin P := FastMM_AllocMem(SizeOf(TMyRecord)); if P <> nil then begin // P^ is now zero-initialized FastMM_FreeMem(P); end; end; ``` -------------------------------- ### Get Current Memory Usage Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/diagnostics.md Returns the total number of bytes of address space currently committed or reserved by FastMM. This includes allocated blocks, management structures, and reserved space. ```Pascal function FastMM_GetCurrentMemoryUsage: NativeUInt; ``` ```Pascal var MemUsage: NativeUInt; begin MemUsage := FastMM_GetCurrentMemoryUsage; WriteLn(Format('Current memory usage: %d bytes (%.2f MB)', [MemUsage, MemUsage / 1024 / 1024])); end; ``` -------------------------------- ### Assign Custom Stack Trace Conversion Function Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/configuration.md Example of assigning a custom function to FastMM_ConvertStackTraceToText. This custom function will be used to convert stack trace addresses to text in leak reports. ```pascal FastMM_ConvertStackTraceToText := MyCustomConversionFunc; FastMM_EnterDebugMode; // Leak reports will use your custom conversion routine ``` -------------------------------- ### Enable Debug Mode Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/00_START_HERE.md Use FastMM_EnterDebugMode and FastMM_ExitDebugMode to enable memory error catching during development. Ensure to wrap your code in a try-finally block. ```pascal begin FastMM_EnterDebugMode; try // Your code here - memory errors will be caught finally FastMM_ExitDebugMode; end; end; ``` -------------------------------- ### Disable Allocated Block Content Erasure - FastMM_EndEraseAllocatedBlockContent Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/debug-mode.md Disables the erasure of newly allocated block content. Must be balanced with FastMM_BeginEraseAllocatedBlockContent calls. Returns True if erasure was active and is now disabled, or False if not installed. ```pascal function FastMM_EndEraseAllocatedBlockContent: Boolean; ``` ```pascal begin FastMM_BeginEraseAllocatedBlockContent; FastMM_EndEraseAllocatedBlockContent; end; ``` -------------------------------- ### Get Heap Status - FastMM Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/diagnostics.md Retrieves detailed heap statistics. This is an expensive operation that requires walking the entire memory pool. The ALockTimeoutMilliseconds parameter specifies the maximum wait time for arena locks. ```pascal function FastMM_GetHeapStatus(ALockTimeoutMilliseconds: Cardinal = 50): THeapStatus; var Status: THeapStatus; begin Status := FastMM_GetHeapStatus; WriteLn(Format('Total Alloc Unit Count: %d', [Status.TotalAllocated])); WriteLn(Format('Total Free Unit Count: %d', [Status.TotalFree])); WriteLn(Format('Free Small Block Unit Count: %d', [Status.FreeSmall])); end; ``` -------------------------------- ### Set Custom Event Log Filename Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/event-logging.md Sets the full path and filename for the event log. Pass nil to revert to the default event log filename. ```pascal procedure FastMM_SetEventLogFilename(APEventLogFilename: PWideChar); begin FastMM_SetEventLogFilename(PWideChar('C:\Logs\MyApp_FastMM.log')); WriteLn('Event log file set to custom location'); end; ``` -------------------------------- ### Get Maximum User Bytes of Memory Block Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/diagnostics.md FastMM_BlockMaximumUserBytes returns the maximum number of bytes that can be safely used within an allocated block. This value is always greater than or equal to the original requested size. ```pascal function FastMM_BlockMaximumUserBytes(APointer: Pointer): NativeInt; ``` ```pascal var P: Pointer; MaxSize: NativeInt; begin P := FastMM_GetMem(256); MaxSize := FastMM_BlockMaximumUserBytes(P); WriteLn(Format('Maximum usable bytes: %d', [MaxSize])); // Safe to use up to MaxSize bytes FastMM_FreeMem(P); end; ``` -------------------------------- ### Exit Minimum Address Alignment (Pascal) Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/optimization-configuration.md Rescinds a prior alignment request. Calls must be balanced with corresponding FastMM_EnterMinimumAddressAlignment calls. ```pascal procedure FastMM_ExitMinimumAddressAlignment(AMinimumAddressAlignment: TFastMM_MinimumAddressAlignment); ``` ```pascal begin FastMM_EnterMinimumAddressAlignment(maa32Bytes); try var P := FastMM_GetMem(1024); // 32-byte aligned // Use P FastMM_FreeMem(P); finally FastMM_ExitMinimumAddressAlignment(maa32Bytes); end; end; ``` -------------------------------- ### Get Memory Manager State Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/state-logging.md Retrieves a detailed breakdown of the memory manager state, including counts and sizes of allocated blocks grouped by block size. Use this to inspect memory usage patterns. ```Pascal procedure FastMM_GetMemoryManagerState( var AMemoryManagerState: TFastMM_MemoryManagerState; ALockTimeoutMilliseconds: Cardinal = 50 ); ``` ```Pascal var State: TFastMM_MemoryManagerState; I: Integer; begin FastMM_GetMemoryManagerState(State); WriteLn(Format('Small block types: %d', [State.SmallBlockTypeCount])); WriteLn(Format('Medium blocks allocated: %d', [State.AllocatedMediumBlockCount])); WriteLn(Format('Large blocks allocated: %d', [State.AllocatedLargeBlockCount])); WriteLn(Format('Total allocated medium: %d bytes', [State.TotalAllocatedMediumBlockSize])); WriteLn(Format('Total allocated large: %d bytes', [State.TotalAllocatedLargeBlockSize])); end; ``` -------------------------------- ### Enabling Memory Leak Summary Logging in FastMM5 Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/errors.md Illustrates how to enable the logging of memory leak summary events. This allows FastMM5 to report detected memory leaks at application shutdown. ```pascal // Add to leak tracking events FastMM_LogToFileEvents := FastMM_LogToFileEvents + [mmetUnexpectedMemoryLeakSummary]; ``` -------------------------------- ### FastMM_ShareMemoryManager Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/memory-manager-installation.md Starts sharing this memory manager instance with other modules in the current process. Only one memory manager may be shared per process, so this function may fail if another memory manager is already being shared. ```APIDOC ## FastMM_ShareMemoryManager ### Description Starts sharing this memory manager instance with other modules in the current process. Only one memory manager may be shared per process, so this function may fail if another memory manager is already being shared. ### Returns `Boolean` — True if this instance is now being shared or was already the shared manager. False if another memory manager is already being shared. ### Example ```pascal begin // Share this memory manager with other modules if FastMM_ShareMemoryManager then WriteLn('Memory manager is now shared') else WriteLn('Another memory manager is already shared'); end; ``` ``` -------------------------------- ### Enable Erasing Allocated Block Content in FastMM Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/debug-mode.md Enables the erasure of newly allocated block content with the debug pattern $90909090. Calls may be nested. Returns True on success, False if this memory manager is not installed. ```Pascal function FastMM_BeginEraseAllocatedBlockContent: Boolean; begin FastMM_BeginEraseAllocatedBlockContent; try var P := FastMM_GetMem(256); // Will be filled with $90909090 // Use P, any uninitialized memory read will have pattern values FastMM_FreeMem(P); finally FastMM_EndEraseAllocatedBlockContent; end; end; ``` -------------------------------- ### Free FastMM Debug Support Library Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/debug-mode.md Unloads the debug support library and resets stack trace handlers. Returns true if the library was freed, false if it was not loaded. ```pascal function FastMM_FreeDebugSupportLibrary: Boolean; ``` ```pascal begin if FastMM_FreeDebugSupportLibrary then WriteLn('Debug support library unloaded') else WriteLn('Debug support library was not loaded'); end; ``` -------------------------------- ### Core Memory Management Functions Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/INDEX.md Functions for basic memory allocation, deallocation, and resizing. ```APIDOC ## FastMM_GetMem() ### Description Allocates a block of memory. ### Method Call ### Parameters None explicitly documented. ### Request Example ``` var ptr: Pointer; begin ptr := FastMM_GetMem(1024); // Use memory FastMM_FreeMem(ptr); end; ``` ## FastMM_FreeMem() ### Description Frees a previously allocated block of memory. ### Method Call ### Parameters - **P** (Pointer) - The pointer to the memory block to free. ### Request Example ``` FastMM_FreeMem(ptr); ``` ## FastMM_ReallocMem() ### Description Resizes a previously allocated block of memory. ### Method Call ### Parameters - **P** (Pointer) - The pointer to the memory block to resize. - **NewSize** (Integer) - The new size in bytes. ### Request Example ``` ptr := FastMM_ReallocMem(ptr, 2048); ``` ## FastMM_AllocMem() ### Description Allocates a block of memory and initializes it to zero. ### Method Call ### Parameters - **Size** (Integer) - The size in bytes to allocate. ### Request Example ``` var ptr: Pointer; begin ptr := FastMM_AllocMem(512); // Use zero-initialized memory FastMM_FreeMem(ptr); end; ``` ``` -------------------------------- ### Get Current User Bytes of Memory Block Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/diagnostics.md Use FastMM_BlockCurrentUserBytes to retrieve the user-requested size of an allocated memory block. Outside of debug mode, this might return the maximum usable size for small and medium blocks. ```pascal function FastMM_BlockCurrentUserBytes(APointer: Pointer): NativeInt; ``` ```pascal var P: Pointer; Size: NativeInt; begin P := FastMM_GetMem(256); Size := FastMM_BlockCurrentUserBytes(P); WriteLn(Format('Current user bytes: %d', [Size])); FastMM_FreeMem(P); end; ``` -------------------------------- ### Enable FastMM5 Debug Mode Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/INTEGRATION_GUIDE.md Activates debug mode for development, enabling full stack traces. Set FASTMM_DEBUG to False for release builds to disable this functionality. ```pascal procedure EnableDebugMode; const FASTMM_DEBUG = True; // Set False for release begin if FASTMM_DEBUG then begin FastMM_EnterDebugMode; FastMM_SetDebugModeStackTraceEntryCount(16); WriteLn('Debug mode enabled with full stack traces'); end; end; procedure DisableDebugMode; begin if FastMM_DebugModeActive then FastMM_ExitDebugMode; end; begin EnableDebugMode; try // Application code finally DisableDebugMode; end; end. ``` -------------------------------- ### Finalize FastMM Memory Manager Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/memory-manager-installation.md Uninstalls FastMM and performs cleanup including memory leak reporting. This function is called automatically during unit finalization unless FastMM_DisableAutomaticInstall is defined. Returns true if FastMM was previously installed and is now uninstalled. ```pascal function FastMM_Finalize: Boolean; ``` ```pascal begin // Manual finalization (only if FastMM_DisableAutomaticInstall is defined) if FastMM_Finalize then WriteLn('FastMM finalized and uninstalled') else WriteLn('FastMM was not the active memory manager'); end; ``` -------------------------------- ### Configure FastMM Error Reporting (Pascal) Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/errors.md Configure FastMM error reporting destinations by assigning event sets to FastMM_MessageBoxEvents, FastMM_LogToFileEvents, or FastMM_OutputDebugStringEvents. ```pascal // Only show dialog boxes for critical errors FastMM_MessageBoxEvents := [mmetDebugBlockDoubleFree, mmetDebugBlockHeaderCorruption]; // Log everything to file FastMM_LogToFileEvents := [mmetDebugBlockDoubleFree, mmetDebugBlockReallocOfFreedBlock, mmetDebugBlockHeaderCorruption, mmetDebugBlockFooterCorruption, mmetDebugBlockModifiedAfterFree, mmetVirtualMethodCallOnFreedObject]; // Send to debugger FastMM_OutputDebugStringEvents := [mmetDebugBlockDoubleFree]; ``` -------------------------------- ### Get Usage Summary - FastMM Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/diagnostics.md Retrieves a summary of memory usage, including allocated bytes, overhead, and efficiency. This is an expensive operation requiring a full pool walk. The ALockTimeoutMilliseconds parameter specifies the maximum wait time for arena locks. ```pascal function FastMM_GetUsageSummary(ALockTimeoutMilliseconds: Cardinal = 50): TFastMM_UsageSummary; var Summary: TFastMM_UsageSummary; begin Summary := FastMM_GetUsageSummary; WriteLn(Format('Allocated: %d bytes', [Summary.AllocatedBytes])); WriteLn(Format('Overhead: %d bytes', [Summary.OverheadBytes])); WriteLn(Format('Efficiency: %.2f%%', [Summary.EfficiencyPercentage])); end; ``` -------------------------------- ### Share Memory Manager with Other Modules Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/memory-manager-installation.md Starts sharing this memory manager instance with other modules in the current process. This function may fail if another memory manager is already being shared. Returns true if this instance is now shared or was already the shared manager. ```pascal function FastMM_ShareMemoryManager: Boolean; ``` ```pascal begin // Share this memory manager with other modules if FastMM_ShareMemoryManager then WriteLn('Memory manager is now shared') else WriteLn('Another memory manager is already shared'); end; ``` -------------------------------- ### Allocate Zero-Initialized Debug Memory Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/debug-memory-management.md Use FastMM_DebugAllocMem to allocate memory that is both zero-initialized and tracked with debug metadata. This is useful for structures where initial zero values are important. ```pascal function FastMM_DebugAllocMem(ASize: NativeInt): Pointer; ``` ```pascal type TDebugData = record Counter: Integer; Values: array[0..99] of Double; end; begin FastMM_EnterDebugMode; try var P := FastMM_DebugAllocMem(SizeOf(TDebugData)); if P <> nil then begin // Memory is zero-initialized and debug-tracked FastMM_DebugFreeMem(P); end; finally FastMM_ExitDebugMode; end; end; ``` -------------------------------- ### Allocate Aligned Memory for SIMD Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/INTEGRATION_GUIDE.md Allocates memory with a specified alignment, crucial for SIMD operations. Use FastMM_EnterMinimumAddressAlignment and FastMM_ExitMinimumAddressAlignment to set the alignment context for memory allocation. ```pascal type PFloat32 = ^Float; function AllocateAlignedArray(Count: Integer): PFloat32; var P: Pointer; begin // Request 16-byte alignment for SSE operations FastMM_EnterMinimumAddressAlignment(maa16Bytes); try // Allocate array of floats (requires alignment) P := FastMM_GetMem(Count * SizeOf(Float)); if P <> nil then Result := P else raise EOutOfMemory.Create('Cannot allocate aligned array'); finally FastMM_ExitMinimumAddressAlignment(maa16Bytes); end; end; procedure ProcessSSEArray; var Data: PFloat32; begin Data := AllocateAlignedArray(1024); try // Data is guaranteed 16-byte aligned for SSE // Perform SIMD operations finally FastMM_FreeMem(Data); end; end; ``` -------------------------------- ### Allocate and Free Memory Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/00_START_HERE.md Use FastMM_GetMem to allocate a specified amount of memory and FastMM_FreeMem to release it. Check the return value of FastMM_GetMem for successful allocation. ```pascal var P: Pointer; begin P := FastMM_GetMem(1024); if P <> nil then begin // Use memory... FastMM_FreeMem(P); end; end; ``` -------------------------------- ### Exit FastMM Debug Mode Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/api-reference/debug-mode.md Exits debug mode. The number of calls must match corresponding FastMM_EnterDebugMode calls. Debug mode is only fully exited when the call count reaches zero. Returns True if debug mode was active and has been exited, or is still active if calls are still pending. Returns False if this memory manager is not installed. ```Pascal function FastMM_ExitDebugMode: Boolean; begin FastMM_EnterDebugMode; FastMM_EnterDebugMode; WriteLn('Debug mode entered twice'); FastMM_ExitDebugMode; // Still in debug mode (one level deep) FastMM_ExitDebugMode; // Now fully exited WriteLn('Debug mode fully exited'); end; ``` -------------------------------- ### TFastMM_UsageSummary Record Source: https://github.com/pleriche/fastmm5/blob/master/_autodocs/types.md Provides a summary of the current memory usage and efficiency. This record is populated by FastMM_GetUsageSummary(). ```pascal type TFastMM_UsageSummary = record AllocatedBytes: NativeUInt; OverheadBytes: NativeUInt; EfficiencyPercentage: Double; end; ```