linux Valgrind -无内存泄漏,但条件跳转或移动取决于未初始化的值

cvxl0en2  于 2022-12-29  发布在  Linux
关注(0)|答案(1)|浏览(111)

我正在创建一个包含链表的数组,我正在尝试消除内存泄漏和未初始化的值。
"条件跳转或移动取决于未初始化的值"
有人知道这是为什么吗?
下面是我的代码:

#include<iostream>
#include<string>
using namespace std;

struct Item
{
    int key;
    string value;
    Item *next;
};

//array for storing items and lists of items 
//- allocate array  
//- create a linked list at array index if needed
Item **items = new Item*[3];

void add_item(int key, string value, int index)
{
    
    //create new item
    Item *it = new Item;
    it->key = key;
    it->value = value;
    it->next = NULL;

    //if there are no items at location
    if(items[index] == NULL)
        items[index] = it;
    //if there is, iterate through linked list and add item at end
    else
    {
        Item* curr = items[index]; //start of linked list

        while(curr->next != NULL)
            curr = curr->next;

        curr->next = it;
    }
}

int main()
{

    Item *curr;

    add_item(1, "Happy", 0);
    add_item(2, "Sad", 0);
    add_item(3, "Laughing", 1);
    add_item(4, "Angry", 2);

    for(int i=0; i<3; i++)
    {
        curr = items[i];

        while(curr != NULL)
        {
            cout<<curr->key<<" "<<curr->value;
            curr = curr->next;
            if(curr != NULL)
                cout<<" --> ";
            else
                cout<<endl;
        }
    }

    //delete memory
    for(int i=0; i<3; i++)
    {
        curr = items[i]; //start of list

        //delete linked list starting at array index
        while(curr != NULL) 
        {
            Item *temp = curr;
            curr = curr->next;
            delete temp;
        }
        
    }
    delete [] items; //delete array 

    return 0;
}

我已经重写了几次程序,老实说我不知道它为什么这么说。

abithluo

abithluo1#

Item **items = new Item*[3];创建了一个包含3个未初始化指针的数组。因此,检查if(items[index] == NULL)在第一次调用时可能不为真。随机值将使程序在while(curr->next != NULL)处崩溃。
您可以通过初始化指针来修复它:最终默认值中的()初始化这些值(例如,在这种情况下为nullptr)。
之后,地址消毒器不再抱怨:https://godbolt.org/z/3xxzYa4Gs

相关问题