簡體   English   中英

內存泄漏? 怎么修?

[英]Memory leak? How to fix?

我有自己的使用LL實現隊列和堆棧的類,源代碼在我的機器上可以正常編譯,但是將其扔到valgrind中后,它顯示出一些內存泄漏

class S{
private:
struct Node{

int value;
Node* next; 

Node(int v, Node* n):value(v), next(n){}
};

Node* head;

S(const S& other) {}
S& operator=(const S& other) {}

public:
S():head(NULL){}


void push(unsigned int data){
    head = new Node(data, head);
}


class Q{
private:
struct Node{

int value;
Node* next;
Node(int v, Node* n):value(v), next(n){}
};

Node* head;
Node* tail;
int size;

Q(const Q& other) {}
Q& operator=(const Q& other) {}

public:
Q():head(NULL), tail(NULL), size(0){}

void push(int data){
    if (head == NULL) head = tail = new Node(data, tail);
    else{
        tail -> next = new Node(data, tail);
        tail = new Node(data, tail);
    }
    size++;
}

瓦爾格隆德

我究竟做錯了什么? 許多幫助將不勝感激:)歡呼

在您的類構造函數中:

PQ(int cap){
capacity = cap;
arr = new int [capacity++];
for (int i= 0; i < capacity; i++)       arr[i] = {0};}

這個:

capacity++

將首先返回容量,然后將其值增加一。 因此,當您在for循環中填充數組時,由於數組大小比容量值小1 ,因此您超出了數組范圍。

這不是“內存泄漏”。

這是內存損壞。 您可以通過盡一切努力來理解C ++中的數組是基於0的,而不是基於1的數組來開始修復它的。 數組的第一個元素是array[0]而不是array[1] ,其他所有內容都基於此。 以下內容基於數組元素以數組元素#1開頭的概念:

int top(){
    return arr[1];
}
void pop(){
    arr[1] = arr[size];

數組的第一個元素是元素#0,而不是元素#1,但這是基於以下概念構造的:數組中的第一個元素是元素#1。

似乎在分配數組大小之前先將其加1是避免進行此調整的一種簡便方法,但此舉只會導致更多的麻煩,困惑和錯誤,稍后再進行。 顯然,這就是為什么構造函數嘗試在分配數組之前增加數組大小的原因:

PQ(int cap){
    capacity = cap;
    arr = new int [capacity++];
    for (int i= 0; i < capacity; i++)       arr[i] = {0};
}

除了它錯誤地增加它。 這是后增量,因此,例如,如果cap為4,則會在capacity增加之前分配new int[4] 下一行嘗試清除數組元素#0到#4,除了數組元素#4不存在,代碼嘗試對其進行初始化,在數組末尾運行,並且valgrind拋出紅色標志。

盡管可以簡單地通過使用前遞增而不是后遞增來解決此問題,但是正確的解決方案是根本不遞增,而是重新組織代碼,以使它遵循C ++數組的自然屬性,它們基於0,而不是基於1。 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM