Strange runtime error


  • 1
    A

    I met a strange run time error for my codes. After investigation, I found the same error can happen on a trivial implementation. Is that a bug?

    class Solution {

    public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
    if (lists.empty()) return nullptr;
    }

    };

    The error is:
    Submission Result: Runtime Error

    Last executed input: [{}]


  • 2

    [{}] does not indicate an empty list, as an empty list is indicated by []. [{}] is in fact a list with the size of one containing a NULL pointer.

    As your program only returns nullptr only when the list is empty, it results in Undefined Behavior for the input [{}], according to ISO C++-98[Section 6.6.3/2].

    A return statement with an expression can be used only in functions returning a value; the value of the expression is returned to the caller of the function. If required, the expression is implicitly converted to the return type of the function in which it appears. A return statement can involve the construction and copy of a temporary object (class.temporary). Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

    Source: StackOverflow


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.