Subject: bug#59874: Segfault from string-ref with negative 'k'

From: Ricardo Wurmus <[email-masked]>
Date: Wed, 07 Dec 2022 11:29:28 +0100

Thank you for reporting this bug.

> i noticed that if i, on my system, run "guile" from a shell and then type into the command prompt that appears,
>
> (string-ref "a string" -1)
>
> guile appears to hang for a few seconds or so, and then prints the message "Segmentation fault (core dumped)".

I can reproduce this on Guix System with guile 3.0.8:

--8<---------------cut here---------------start------------->8---
guile --no-auto-compile --debug
GNU Guile 3.0.8
Copyright (C) 1995-2021 Free Software Foundation, Inc.

Guile comes with ABSOLUTELY NO WARRANTY; for details type `,show w'.
This program is free software, and you are welcome to redistribute it
under certain conditions; type `,show c' for details.

Enter `,help' for help.
scheme@(guile-user)> (string-ref "a string" -1)
Segmentation fault
--8<---------------cut here---------------end--------------->8---

But:

--8<---------------cut here---------------start------------->8---
$ guile -c '(string-ref "a string" -1)'
Backtrace:
In ice-9/boot-9.scm:
  1752:10  6 (with-exception-handler _ _ #:unwind? _ #:unwind-for-type _)
In unknown file:
           5 (apply-smob/0 #<thunk 7f3912dd02e0>)
In ice-9/boot-9.scm:
    724:2  4 (call-with-prompt ("prompt") #<procedure 7f3912de2c60 at ice-9/eval.scm:330:13 ()> #<procedure default-prompt-handler (k proc)>)
In ice-9/eval.scm:
    619:8  3 (_ #(#(#<directory (guile-user) 7f3912dd5c80>)))
In ice-9/command-line.scm:
   185:19  2 (_ #<input: string 7f3912dcf850>)
In unknown file:
           1 (eval (string-ref "a string" -1) #<directory (guile-user) 7f3912dd5c80>)
           0 (string-ref "a string" -1)

ERROR: In procedure string-ref:
Value out of range 0 to< 7: -1
--8<---------------cut here---------------end--------------->8---

-- 
Ricardo