我在删除动态内存方面遇到了一些麻烦。我有100个整数的数组,但后来在运行时超过了一半的数组没有使用,所以我想释放那个内存。这是我的尝试。谁能解释为什么我会收到错误?谢谢!
void dynSybarrDel(){
int* intArr = new int[100];
int* subArr = (intArr + 50);
delete subArr;
}
答案 0 :(得分:-1)
但是如果你对内存进行malloc,你可以使用realloc删除到最后:
let mapItems
state
index
handlerfn =
state
|> Array.indexed
|> Array.map (
fun (i, item) ->
if index < 0 then
handlerfn item
else if i = index then
handlerfn item
else
item)
...
let handleAction
(mapItems : 'a [] -> int -> ('a -> 'a) -> 'a [])
state
action =
match action with
|Pausable action -> //actions specific to pausable stopwatch
let handler =
mapItems
state
action.index
match action.``type`` with
| Pause current ->
handler//call handler with state
(fun state ->
(handlePause current state))
| StopWatch action -> //actions from stop watch
let handler =
mapItems
state
action.index
match action.``type`` with
| Start current ->
handler//call handler with state
(fun state ->
//would use some of stopwatch handlers here
{state with
status ="started"
})
要在#include <cstring>
void dynSybarrDel(){
int* intArr = (int*)malloc(100 * sizeof(int));
int* subArr = (intArr + 50);
intArr = realloc(intArr, (subArr - intArr)*sizeof(int));
};
内存中初始化特定类型的数组元素,请执行此操作(但是,如果您知道在读取之前将其覆盖,则无需在int或其他内置类型上执行此操作否则会有随机值):
malloc
要毁灭:
new(elementPtr) myType("parameter1", 2.0);
elementPtr->~myType();
只是迭代的元素地址,如下所示:
elementPtr
但是,如果您可以使用MyType* elementPtr = myArr;
for(int i = arrSize; i; --i, ++elementPtr)
,则可以执行更多操作:
std::vector
你甚至可以删除矢量中的一个部分:
#include <vector>
void dynSybarrDel(){
std::vector<int> intArr(100);
auto subArr = intArr.begin() + 50;
intArr.erase(subArr, intArr.end());
};
产生输出:
0 1 2 3 4 5 6 7 8 9
0 1 2 8 9
答案 1 :(得分:-1)
这里的代码:int* intArr = new int[100];
告诉编译器给出4 * 100的内存空间。你基本上把它分配给你自己使用 - 没有人可以在你的程序旁边使用它,直到它回到内存池。
因为编译器已经完成了你告诉他做的事情(并给了你记忆)。你不能要求他在运行时忽略它。 但是,你可以要求占用一半的空间并在以后的程序中分配新的内存。
重新分配新内存时,编译器首先尝试查看当前内存的扩展名是否空闲且大小合适。如果是这样,它会为您提供当前数组延续的地址,如果不是,它会将当前数组复制到另一个具有足够空间的内存地址(如果可能)。