Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

PDF stack overflow and underflow

1 min read

The PDF format makes extensive use of stacks.

A stack is like a pile of books. If you add an item it goes on the top of the pile and it will be the first item retrieved. It is the opposite of a queue where you join the end and have to wait your turn to reach the front of the queue.

A common use of a stack in the PDF file format is to save values – you can push a value like the GraphicsState onto the stack, make changes and then retrieve the original by pulling the saved value back off the stack. It works  perfectly with recursive structures where you can keep pushing and then pulling.

But if you put more values onto the pile than it can hold this is stack overflow, while trying to pull items from an empty stack in stack underflow. This is generally due to software bugs or poor coding – it should not happen. Which is one reason why it is the name adopted by the excellent programming question site stackoverflow.

But it does happen so what do you do if you try to get a value from an empty queue – there is nothing in the pile and you try to retrieve a value? There are THREE possible options and I have been looking for examples to see which approach to use:-

1. Fail. The software stops and does not display the PDF file.

2. Ignore it. We just carry on and use the current value rather than replacing it with the value from the stack.

3. Use the default value. If we cannot get the old value from the stack we could reset the value to the original default settings.

I have some debug code in the test build of our PDF library to show such an event and it finally found me a file last week with a stack underflow. And it appears the correct answer is 3.



Do you need to process or display PDF files?

Find out why you should be using IDRSolutions software
Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

How to insert an image into a PDF

Recently, we released JPedal 2023.07 which contains the ability to insert images into PDF files. All you need is a copy of JPedal, a...
Jacob Collins
18 sec read