Can calling this method in a loop cause a stack overflow? And if so, how to solve it?

Queue Queue::operator <<(Time &time) { Element *temp = new Element; temp->time = time; temp->next = NULL; if (head != NULL) { tail->next = temp; tail = temp; } else head = tail = temp; size++; return *this; } 
  • No, this code only uses a bunch that can overflow. The stack in it does not grow during the cycle. You are allocated to the stack only the variable Element *temp , which when exited is immediately destroyed and so will be in a circle. - Alex Krass
  • Why do you sin on him? Maybe there is something else in this cycle that is ... dubious? - Harry
  • MVS knocks me out with this unhandled exception at 0x777EDEDF (ntdll.dll) in ConsoleApplication10.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x00192FFC). When you try to call this method. - HadJower5
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

The question is somehow incorrect. If you cause any creation of new items that are allocated to memory, in a cycle, then sooner or later, the memory will be full, it will cause a stack overflow. If you need to call this method in a small cycle, then everything will work fine, but it still depends on the machine. And if an endless loop, everything is clear.

For safety, I advise you to make some kind of limit on the size of the queue. And when you try to add a new item to the queue, check the size.