首页 > 解决方案 > I have an error in my c++ code Adress Sanitizer errer keeps poping up

问题描述

I keep getting this error

==27398==ERROR: AddressSanitizer: SEGV on unknown address 0x000000000030 (pc 0x55b3e7f5a676 bp 0x7ffc3378c600 sp 0x7ffc3378c520 T0)
==27398==The signal is caused by a WRITE memory access.
==27398==Hint: address points to the zero page.
    #0 0x55b3e7f5a675 in Inventory::addItemStackNoCheck(ItemStack) /home/gmeadows/cs330/Ass_1/Inventory.cpp:190
    #1 0x55b3e7f59e0d in Inventory::Inventory(Inventory const&) /home/gmeadows/cs330/Ass_1/Inventory.cpp:58

Line 190 is in my constructor and is a call to a function that line 58 is in

constructor

Inventory::Inventory(const Inventory &src)
{
    // @todo implement this function

    //initialize every private data member

    this->head     = nullptr;
    this->tail     = nullptr;
    this->occupied = src.occupied;
    this->slots    = src.slots;
 
    // Start the Copy Operations
    Node* srcIt = src.head;

    while (srcIt != nullptr) {
        this->addItemStackNoCheck(srcIt->data);  // <-- line 58

        srcIt = srcIt->next;
    }
}

this is the function addtimestacknocheck

void Inventory::addItemStackNoCheck(ItemStack itemStack)
{
    // @todo implement this function

    Node* new_node = nullptr;

    new_node = new Node(itemStack);

    //if inventory is empty

    if(this->occupied == 0)
    {
        //head and tail are the added itemstack

        this->head = new_node;
        this->tail = new_node;

    }

    //with 1 or more itemstacks
    else
    {
        (this->tail)->next = new_node;   /// <-- line 190
        this->tail = new_node;
    }

    this->occupied++;

    new_node = nullptr;
}

Line 190 is the (this->tail)->next = new_node;
line 58 is this->addItemStackNoCheck(srcIt->data);

I have done alot of research on this error and cant seem to figure out why it keeps happening.

标签: c++

解决方案


你想看节点是否为空,而不是数据成员占用是否为0。

if(this->head = nullptr)

此外,您将希望在您的复制构造函数中拥有:

this->occupied = 0;

推荐阅读