Fix list_copy_head() with empty Lists
authorDavid Rowley
Thu, 20 Apr 2023 22:02:25 +0000 (10:02 +1200)
committerDavid Rowley
Thu, 20 Apr 2023 22:02:25 +0000 (10:02 +1200)
list_copy_head() given an empty List would crash from trying to
dereference the List to obtain its length.  Since NIL is how we represent
an empty List, we should just be returning another empty List in this
case.

list_copy_head() is new to v16, so let's fix it now before too many people
start coding around the buggy NIL behavior.

Reported-by: Miroslav Bendik
Discussion: https://postgr.es/m/CAPoEpV02WhawuWnmnKet6BqU63bEu7oec0pJc=nKMtPsHMzTXQ@mail.gmail.com

src/backend/nodes/list.c

index 75aa5baa8072c7da1532c0a2c7db4328a4409676..90f93e893cfdce5c467443f7a2db2f18bcb80892 100644 (file)
@@ -1553,11 +1553,11 @@ list_copy_head(const List *oldlist, int len)
 {
    List       *newlist;
 
-   len = Min(oldlist->length, len);
-
-   if (len <= 0)
+   if (oldlist == NIL || len <= 0)
        return NIL;
 
+   len = Min(oldlist->length, len);
+
    newlist = new_list(oldlist->type, len);
    memcpy(newlist->elements, oldlist->elements, len * sizeof(ListCell));