-1
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?

hoo
  • 67
  • 4
  • 2
    C++ does not have segmentation faults, so there is no reason in C++ that they occur. Instead C++ just says that your code has *undefined behaviour* due to the *dangling pointer*. A dangling pointer is a pointer pointing at a no longer valid object. Undefined behaviour means exactly what it says, a segmentation fault is one kind of undefined behaviour but so is any other behaviour you can think of. – john Jan 19 '23 at 06:08
  • 1
    [std::queue](https://en.cppreference.com/w/cpp/container/queue) is a container adaptor which uses [std::deque](https://en.cppreference.com/w/cpp/container/deque) by default. The doc. of [std::deque::pop_front](https://en.cppreference.com/w/cpp/container/deque/pop_front) states _Iterators and references to the erased element are invalidated._ Invalid reference means as well that pointers to that (referenced) object become invalid. – Scheff's Cat Jan 19 '23 at 06:20
  • 1
    What that means is you have to copy/move what you pop. You can't keep a reference or a pointer to an object you popped of the stack (it no longer exists after pop has been called)>. So read the documentation on what you use. Side note : stop using `using namespace std;` – Pepijn Kramer Jan 19 '23 at 06:21
  • do I have to stop using `using namespace std;` in online PS as well?? – hoo Jan 19 '23 at 06:51
  • Side notes: 1) [UB](https://en.cppreference.com/w/cpp/language/ub) 2) [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) 3) [UndefinedBehaviorSanitizer](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html) 4) [AddressSanitizer](https://en.m.wikipedia.org/wiki/AddressSanitizer) – Jesper Juhl Jan 19 '23 at 12:28

1 Answers1

1

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.

hoo
  • 67
  • 4
  • 2
    `cplusplus.com` doesn't have a good reputation among some (or most?) members of this community. I'd recommend [cppreference.com](https://cppreference.com) instead. – Scheff's Cat Jan 19 '23 at 13:44