Line data Source code
1 : /**
2 : * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3 : * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4 : * CANN Open Software License Agreement Version 2.0 (the "License").
5 : * Please refer to the License for details. You may not use this file except in compliance with the License.
6 : * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7 : * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8 : * See LICENSE in the root of the software repository for the full text of the License.
9 : */
10 : #include <cerrno>
11 : #include "securec.h"
12 : #include "log/adx_log.h"
13 : #include "memory_utils.h"
14 : namespace Adx {
15 : /**
16 : * @brief malloc memory and memset memory
17 : * @param size: the size of memory to malloc
18 : *
19 : * @return
20 : * NULL: malloc memory failed
21 : * not NULL: malloc memory succ
22 : */
23 194 : IdeMemHandle IdeXmalloc(size_t size)
24 : {
25 : errno_t err;
26 :
27 194 : if (size == 0) {
28 0 : return nullptr;
29 : }
30 :
31 194 : IdeMemHandle val = malloc(size);
32 194 : if (val == nullptr) {
33 0 : IDE_LOGE("ran out of memory while trying to allocate %zu bytes", size);
34 0 : return nullptr;
35 : }
36 :
37 194 : err = memset_s(val, size, 0, size);
38 194 : if (err != EOK) {
39 0 : free(val);
40 0 : val = nullptr;
41 0 : IDE_LOGE("memory clear failed, err: %d", err);
42 0 : return nullptr;
43 : }
44 :
45 194 : return val;
46 : }
47 :
48 : /**
49 : * @brief realloc memory and copy ptr to new memory address
50 : * @param ptr: the pre memory
51 : * @param ptrsize: the pre memory size
52 : * @param size: the new memory size
53 : *
54 : * @return
55 : * NULL: malloc memory failed
56 : * not NULL: malloc memory succ
57 : */
58 6 : IdeMemHandle IdeXrmalloc(const IdeMemHandle ptr, size_t ptrsize, size_t size)
59 : {
60 6 : IdeMemHandle val = nullptr;
61 6 : if (size == 0) {
62 0 : return nullptr;
63 : }
64 :
65 6 : if (ptr != nullptr) {
66 1 : size_t cpLen = (ptrsize > size) ? size : ptrsize;
67 1 : val = IdeXmalloc(size);
68 1 : if (val != nullptr) {
69 1 : errno_t err = memcpy_s(val, size, ptr, cpLen);
70 1 : if (err != EOK) {
71 0 : IDE_XFREE_AND_SET_NULL(val);
72 0 : return nullptr;
73 : }
74 : }
75 : } else {
76 5 : val = IdeXmalloc(size);
77 : }
78 :
79 6 : return val;
80 : }
81 :
82 : /**
83 : * @brief free memory
84 : * @param ptr: the memory to free
85 : *
86 : * @return
87 : */
88 202 : void IdeXfree(const IdeMemHandle ptr)
89 : {
90 202 : if (ptr != nullptr) {
91 196 : free(ptr);
92 : }
93 202 : }
94 : }
|