gpt4 book ai didi

c++ - 在 C++ 中使用指针时的内存管理

转载 作者:行者123 更新时间:2023-11-27 23:17:08 25 4
gpt4 key购买 nike

我有这些情况,我想知道我是否正确地管理了我的内存。当我启动可执行文件时,我在任务管理器中观察了内存消耗,并看到内存如何没有恢复到初始数量,这让我怀疑我没有在需要的地方清除内存。因此,在第一种情况下,我有一个向动态数组添加新元素的函数:

struct Color {
int R;
int G;
int B;
}

int TotalColors;
Color* Rainbow;

void AddColor(Color NewColor) {
// So, I create a new array of size TotalColors+1
Color* NewRainbow = new Color[TotalColors+1];
// Now I add the existing elements
for (int i=0; i<TotalColors; i++) {
NewRainbow[i] = Rainbow[i];
}
// And lastly, I add the new element
NewRainbow[TotalColors] = NewColor;
// Now, I assign the NewRainbow to Rainbow (I don't know if it's correct)
Rainbow = NewRainbow;
}

那么,在这种情况下,您认为我错过了什么吗?这是可行的,但我想确保从内存中删除未使用的内容。我还有一个删除元素的函数,如下所示:

void RemoveColor(Color Removable) {
// Again, I create a new array of size TotalColors-1
Color* NewRainbow = new Color[TotalColors-1];
// I scan the list and add only those elements which are not 'Removable'
for (int i=0; i<TotalColors; i++) {
// Let's suppose that Removable exists in the list
if (Rainbow[i].R != Removable.R && Raibow[i].G != Removable.G && ... {
NewRainbow [i] = Rainbow[i];
}
}
// Again, the same operation as above
NewRainbow[TotalColors] = NewColor;
Rainbow = NewRainbow;
}

在这种情况下,我不知道 Rainbow[Removable] 会发生什么,我的意思是,数组中被删除的元素。最后一种情况是,我尝试将元素的指针从数组发送到函数。

Color* GetColor(int Index) {
Color* FoundColor;
// Scan the array
for (int i=0; i<TotalColors; i++) {
if (i == Index) FoundColor = &Rainbow[i];
}
return FoundColor;
}

// And I use it like this
void ChangeColor(int Index) {
Color* Changeable;
Changeable = GetColor(Index);
SetRGB(Changeable, 100, 100, 100);
}

// And this is what changes the value
void SetRGB(Color* OldRGB, int R, int G, int B) {
(*oldRGB).R = R;
(*oldRGB).G = G;
(*oldRGB).B = B;
}

就是这样。所以,这可行,但我不确定是否有这么多指针我没有忘记删除一些东西。例如,当我 RemoveColor 时,我没有看到内存发生变化(也许某些字节没有什么区别),我只是希望专业人士告诉我是否遗漏了什么。谢谢!

最佳答案

在第一个函数 AddColor() 中,您没有删除之前分配的内存。

Rainbow = NewRainbow; // leaking the memory Rainbow was previously pointing to.

将最后一行更改为:

delete[] Rainbow;
Rainbow = NewRainbow;

RemoveColor() 相同

任何时候你使用new操作符,它都需要一个相应的delete。此外,如果您像您的情况一样使用 new[] 分配数组,则它必须具有相应的 delete[]

关于c++ - 在 C++ 中使用指针时的内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15705385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com