PDF stack overflow and underflow

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.

Related Posts:

The following two tabs change content below.

Mark Stephens

System Architect and Lead Developer at IDRSolutions
Mark Stephens has been working with Java and PDF since 1999 and has diversified into HTML5, SVG and JavaFX. He also enjoys speaking at conferences and has been a Speaker at user groups, Business of Software, Seybold and JavaOne conferences. He has a very dry sense of humor and an MA in Medieval History for which he has not yet found a practical use.
Markee174

About Mark Stephens

Mark Stephens has been working with Java and PDF since 1999 and has diversified into HTML5, SVG and JavaFX.

He also enjoys speaking at conferences and has been a Speaker at user groups, Business of Software, Seybold and JavaOne conferences. He has a very dry sense of humor and an MA in Medieval History for which he has not yet found a practical use.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>