forked from hw-native-sys/simpler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory_allocator.cpp
More file actions
66 lines (54 loc) · 1.86 KB
/
memory_allocator.cpp
File metadata and controls
66 lines (54 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* Copyright (c) PyPTO Contributors.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
* -----------------------------------------------------------------------------------------------------------
*/
/**
* Memory Allocator Implementation (Simulation)
*
* Uses standard malloc/free to simulate device memory operations.
*/
#include "host/memory_allocator.h"
#include <cstdlib>
#include "common/unified_log.h"
MemoryAllocator::~MemoryAllocator() { finalize(); }
void *MemoryAllocator::alloc(size_t size) {
void *ptr = std::malloc(size);
if (ptr == nullptr) {
LOG_ERROR("malloc failed (size=%zu)", size);
return nullptr;
}
// Track the pointer
ptr_set_.insert(ptr);
return ptr;
}
int MemoryAllocator::free(void *ptr) {
if (ptr == nullptr) {
return 0;
}
// Check if we're tracking this pointer
auto it = ptr_set_.find(ptr);
if (it == ptr_set_.end()) {
// Not tracked by us, don't free
return 0;
}
// Free the memory
std::free(ptr);
// Remove from tracking set
ptr_set_.erase(it);
return 0;
}
int MemoryAllocator::finalize() {
// Free all remaining tracked pointers
for (void *ptr : ptr_set_) {
std::free(ptr);
}
// Clear the set (empty set makes subsequent finalize() calls a no-op)
ptr_set_.clear();
return 0;
}