Search code examples
c++stlqueuestackdynamic-memory-allocation

segmentation fault after popping the element that has been pointed to by


typedef struct { int a; int b; int c; int d } A;
queue <A> q;
A* ptr;

q.push({1,2,3,4});
ptr = &(q.front());
q.pop();

ptr->a; 
...

I figured out that this code might cause segmentation fault. because ptr ends up pointing to the popped element.

but I don't know the exact reason why this happens. I just presume that pop operation interally deallocates the memory for the popped. Is my presumption right? or any other reasons?


Solution

  • In c++ documents(https://cplusplus.com/reference/queue/queue/pop/)

    std::queue::pop is described as


    Removes the next element in the queue, effectively reducing its size by one. The element removed is the "oldest" element in the queue whose value can be retrieved by calling member queue::front.

    This calls the removed element's destructor.

    This member function effectively calls the member function pop_front of the underlying container object.


    so pointing to the popped element is invalid.