Is it possible as a result of the xor, and get an invalid pointer?

245 Views Asked by At

I write code for a xor linked list. I have a function where I get a pointer, using the property C.link = A XOR B. Here the code of the this function

template <class T>
Node<T>* List<T>::get_next(Node<T>* curr, Node<T>* prev)
{
    assert(curr != 0);
    return (Node<T>*)((int)prev ^ (int)curr->np);
}

But in the end get a segmentation fault.Debugging with GDB has shown that the reason for this is the line return (Node<T>*)((int)prev ^ (int)curr->np); in variables such values

p *prev
$6 = {data = 2, np = 0x60}
p *curr
$7 = {data = 12, np = 0x804c058}

In the end of xor

p ((int)prev ^ (int)curr->np)
$8 = 16

In my opinion there is not valid pointer, and so it follows segmentation fault. how can I fix it? Thanks

Тhe problem is solved.The problem was in the assignment operator

template <class T>
List<T>& List<T>::operator=(const List& l)
{
    if(this == &l)
    {
        return *this;
    }
    delete this->m_head;
    delete this->m_tail;
    this->m_size = l.m_size;
    this->m_head = new Node<T>(l.m_head->data);
    this->m_tail = new Node<T>(l.m_tail->data);
    this->m_head = l.m_head;// problem here
    this->m_tail = l.m_tail;// and here
    return *this;
}

I removed these 2 lines and the problem disappeared.

int main()
{
    List<int> l;
    l.insertAtBack(5);
    l.insertAtBack(4);
    l.insertAtBack(8);
    l.insertAtBack(9);
    l.insertAtBack(2);
    l.insertAtBack(12);
    List <int> i;
    i = l;
    i.insertAtBack(19);
    l.insertAtBack(21);     
    i.traverse();
    l.traverse();
    if(i == l)
    {
        std::cout << "Objects is equal :)" << std::endl;
    }
    else
    {
        std::cout << "Objects is not equal :)" << std::endl;
    }
    return 0;
}

Main program was called the assignment operator and assigns the head and tail values of the old object to the new object.

1

There are 1 best solutions below

0
cHao On
  • Use intptr_t rather than int, if you have it... int isn't necessarily big enough to hold a pointer, particularly on 64-bit systems. In older compilers, size_t is more likely to be big enough.
  • It looks like curr is either pointing at the last element of the list, or at something outside of it. (np being that huge typically means either that it's XORed with a null pointer, or it wasn't set properly.) Take a look at how you're figuring np to set it in the first place; there's something odd there.