src/print.c:print_object() has this code:
1570 if (NILP (Vprint_circle) && NILP (Vprint_gensym))
[...]
1581 being_printed[print_depth] = obj;
[...]
1611 print_depth++;
1612
1613 /* See similar code in print_preprocess. */
1614 if (print_depth > PRINT_CIRCLE)
1615 error ("Apparently circular structure being printed");
Note that being_printed[print_depth] is assigned to /before/ print_depth is checked for exceeding PRINT_CIRCLE (the declared size of being_printed). Here's a snippet of elisp that exhibits the bug:
(let ((print-circle nil)
(i 0))
(require 'cl)
(setq x '(a b))
(while (< i 200)
(incf i)
(setq x `(,x)))
(prin1-to-string x))
This errors with "Apparently circular structure being printed". So far so good. Now evaling:
(prin1-to-string "hello")
errors with "Lisp nesting exceeds `max-lisp-eval-depth`" even though it should be an easy thing to print!
Groveling with gdb shows that Vprin1_to_string_buffer gets overwritten during the deep prin1 because of the bug above and instead of pointing at the " prin1" buffer it has a value that pp's as a long chain of "[[[[[["'s and errors out before completing the pretty-print.
Moving the guard check on print_depth above the assignment (and changing > to >= because it's now above the print_depth++) makes the first elisp snippet innocuous - eval'ing it still errors out about the apparently circular structure, but subsequent prin1-to-string's work just fine.
Patch attached.
FWIW, I discovered the bug because using emacs-jabber was making my emacs sessions unstable (at some point random standard elisp functions would start failing). It turned out that one of its variables (jabber-connections) has a deeply-enough nested component that this bug is triggered if it is prin1'd.
Cheers,
-a