简体   繁体   English

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

[英]Memory management when working with pointers in C++

I have these scenarios and I want to know if I manage my memory correctly. 我有这些情况,我想知道是否正确管理我的内存。 I watch the memory consumption in the Task Manager when I start the executable and see how memory is not popped back to the initial amount, which leads me to suspect that I don't clear memory where is needed. 启动可执行文件时,我在任务管理器中查看了内存消耗情况,并看到内存没有弹出回到初始数量,这使我怀疑我没有在需要的地方清除内存。 So, in this first case I have a function that adds a new element to a dynamic array: 因此,在第一种情况下,我有一个向动态数组添加新元素的函数:

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;
}

So, in this case, do you think I miss something? 那么,在这种情况下,您认为我错过了什么吗? This is working but I want to make sure the unused stuff is removed from memory. 这是可行的,但是我想确保未使用的东西从内存中删除。 I also have a function to remove an element, which looks like this: 我还有一个删除元素的功能,如下所示:

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;
}

In this case, I don't know what happens with Rainbow[Removable], I mean, the element of the array that is removed. 在这种情况下,我不知道Rainbow [Removable]会发生什么,我的意思是删除了数组的元素。 And the last case, is this, where I try to send the pointer of an element from the array to a function. 最后一种情况是,我尝试将元素的指针从数组发送到函数。

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;
}

And this is it. 就是这样。 So, this works but I am not sure if with so many pointers I didn't forget to delete something. 因此,这可行,但是我不确定如果有那么多指针,我是否会忘记删除某些内容。 For example, when I RemoveColor I don't see the memory changed (maybe some bytes don't make the difference) and I just want some professional eye to tell me if I missed something. 例如,当我使用RemoveColor时,我看不到内存发生了变化(也许有些字节没有影响),我只是想让专业的眼睛告诉我是否错过了某些事情。 Thanks! 谢谢!

In the first function AddColor() you are not deleting the previously allocated memory. 在第一个函数AddColor()您不会删除先前分配的内存。

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

Change that last line to: 将最后一行更改为:

delete[] Rainbow;
Rainbow = NewRainbow;

Same thing with RemoveColor() RemoveColor()相同

Any time you use the new operator it needs to have a corresponding delete . 每当您使用new运算符时,都需要进行相应的delete Also, if you are allocating an array with new[] as in your case, it must have a corresponding delete[] . 另外,如果您要分配带有new[]的数组,则必须具有相应的delete[]

In order not to worry whether you've forgotten to delete a pointer, you shouldn't use plain pointers. 为了不担心您是否忘记删除指针,不应使用普通指针。 Instead, use smart pointers such as 相反,请使用智能指针,例如

std::shared_ptr
std::unique_ptr
etc.

or, if you don't have C++11 yet, use 或者,如果您还没有C ++ 11,请使用

boost::shared_ptr
boost::scoped_ptr

More on smart pointers, see Wikipedia and the specific documentation. 有关智能指针的更多信息,请参见Wikipedia和特定文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM