Malloc(long, int, Allocator)
Allocates a block of memory of a specified size and alignment.
Read time 1 minuteLast updated 13 days ago
Definition
- Type: Method
- Namespace: Unity.Collections.LowLevel.Unsafe
- Assembly: UnityEngine.CoreModule
public static void* Malloc(long size, int alignment, Allocator allocator)
Parameters
Returns
Type | Description |
|---|---|
| void* | A pointer to the allocated memory block. Manage this pointer carefully to prevent memory leaks and ensure proper deallocation. |
Remarks
The method allocates a block of unmanaged memory. It allows developers to specify the size in bytes and the alignment of the memory block. This method is critical in performance-critical applications where precise memory control is required.
MallocThe memory allocated is not initialized to zero. Ensure that you free the allocated memory with UnsafeUtility.Free when it is no longer needed.
using UnityEngine;using Unity.Collections;using Unity.Collections.LowLevel.Unsafe;public class MallocExample : MonoBehaviour{ void Start() { // Specify the number of elements int numElements = 10; // Allocate memory for an array of integers unsafe { int* array = (int*)UnsafeUtility.Malloc(numElements * sizeof(int), UnsafeUtility.AlignOf<int>(), Allocator.Temp); // Initialize the array with some values for (int i = 0; i < numElements; i++) { array[i] = i * 2; } // Output the contents of the array for (int i = 0; i < numElements; i++) { Debug.Log(array[i]); // Expected output: 0, 2, 4, 6, ..., 18 } // Free the allocated memory UnsafeUtility.Free(array, Allocator.Temp); } }}
Additional Resources: UnsafeUtility.MallocTracked, UnsafeUtility.FreeTracked.