简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM