Hallocy/Docs/MemoryManagement.md

2.9 KiB

Allocator

This part of the library implements custom memory management functions for both windows and linux devices.

Featurs

  • Setting memory
  • Copying memory
  • Moving memory
  • Comparing memory

Usage

Error handling

When using hallocy_set_memory, hallocy_copy_memory or hallocy_move_memory they will return a HallocyError. This error should be handled correctly to avoid any futher problems.

Functions

Set memory

Sets specified block of memory to specified value.

HallocyError hallocy_set_memory(void *destination, int value, const size_t size);

Args:

  • destination: The memory to set the value of.
  • value: The value to set the memory in destination to.
  • size: The size of the memory in bytes to set the value of.

Returns:

  • HALLOCY_ERROR_NONE: Successfully set memory.
  • HALLOCY_ERROR_INVALID_POINTER: Invalid pointer was given.

Copy memory

Copies memory from one pointer to another pointer.

HallocyError hallocy_copy_memory(void *destination, void *source, const size_t size);

Args:

  • destination: The memory to copy the values to.
  • source: The memory to copy the values from.
  • size: The size of the memory in bytes to copy the value to.

Returns:

  • HALLOCY_ERROR_NONE: Successfully copied memory.
  • HALLOCY_ERROR_INVALID_POINTER: Invalid pointers where given.

Move memory

Copies memory from one pointer to another pointer. Unlike the hallocy_copy_memory function this function will handle overlapping memory right.

HallocyError hallocy_move_memory(void *destination, void *source, const size_t size);

Args:

  • destination: The memory to copy the values to.
  • source: The memory to copy the values from.
  • size: The size of the memory in bytes to copy the value to.

Returns:

  • HALLOCY_ERROR_NONE: Successfully moved memory.
  • HALLOCY_ERROR_INVALID_POINTER: Invalid pointers where given.

Compare memory

bool hallocy_compare_memory(void *left_side, void *right_side, const size_t size);

Args:

  • left_side: The memory to compare with the right side.
  • right_side: The memory to compare with the left side.
  • size: The size of the memory in bytes to compare the value to.

Returns: True if both pointers contain same content, else returns false.

Example usage

#include <Hallocy/Core/Allocator.h>
#include <Hallocy/Core/Memory.h>
#include <Hallocy/Utils/Error.h>

int main() {
    char *allocated_memory = hallocy_malloc(128 * sizeof(char));
    if (allocated_memory == NULL) {
        return -1;
    }

    HallocyError error = hallocy_memory_set(allocated_memory, 'T', 127);
    if (error != HALLOCY_ERROR_NONE) {
        return -1; // Check type of error here instead of returning -1 imidiatly.
    }

    error = hallocy_free(allocated memory);
    if (error != HALLOCY_ERROR_NONE) {
        return -1; // Check type of error here instead of returning -1 imidiatly.
    }

    return 0;
}