std/memory.rave
April 10, 2026 ยท View on GitHub
std::malloc
Returns a pointer to the memory allocated on the heap.
Example:
int* ptr = cast(int*)std::malloc(sizeof(int) * 8);
std::amalloc
Returns an aligned pointer to the memory allocated on the heap.
Example:
float* bow = cast(float*)std::amalloc(8, sizeof(float) * 4); // 8-byte alignment
std::free
Frees up the memory in the passed pointer.
Example:
char* ptr = std::malloc(64);
std::free(ptr);
std::realloc
Returns the pointer to the memory with the new size.
Example:
long* foo = cast(long*)std::malloc(128);
std::realloc(cast(char*)foo, 256);
std::calloc
Returns a pointer to zero-initialized memory. The total size is calculated as num * size. Equivalent to malloc followed by memset to zero.
Example:
int* arr = cast(int*)std::calloc(4, 64); // 64 ints, all set to 0
std::memcpy, std::memmove, std::memcmp, std::memset
These functions are designed to work with pointers in the same way as in C.
std::memcpy - Copying bytes from one pointer to another.
std::memmove - Moving bytes from one pointer to another.
std::memcmp - Comparing pointers by a certain number of bytes.
std::memset - Setting a certain value for a certain number of bytes in the pointer.
Example:
char* ptr1 = std::malloc(4);
char* ptr2 = std::malloc(7);
for (int i=0; i<4; i++) ptr1[i] = '0';
for (int i=0; i<7; i++) ptr2[i] = '1';
// ptr1: 0 0 0 0
// ptr2: 1 1 1 1 1 1 1
std::memcpy(ptr1, ptr2, 2); // ptr1: 1 1 0 0
if (std::memcmp(ptr1, ptr2, 2)) {
// True (1 1 with 1 1)
std::memset(ptr2, 0, 7); // ptr2: 0 0 0 0 0 0 0
}
std::swap
Swap a certain number of bytes in both pointers.
Example:
char* ptr1 = std::malloc(2);
char* ptr2 = std::malloc(2);
for (int i=0; i<2; i++) {
ptr1[i] = 'A';
ptr2[i] = 'B';
}
// ptr1: A A
// ptr2: B B
std::swap(ptr1, ptr2, 2);
// ptr1: B B
// ptr2: A A
std::new
It has the same return value as std::malloc, but it immediately returns the required pointer type and allows you to specify the number of such elements.
Example:
// malloc version
int* ptr1 = cast(int*)std::malloc(4);
// std::new version
int* ptr2 = std::new<int>();
std::anew
It has the same return value as std::new, but the returned pointer is aligned.
Example:
double* foo = std::anew<double>(16, 4); // 16-byte alignment
std::pair
This structure allows you to combine any two types of data into one.
Example:
std::pair<float, char> foo = std::pair<float, char>(0f, 10c);
foo.first += 10f;
foo.second -= 10c;