LeetCode 941题Valid Mountain Array的C语言实现出现Heap buffer overflow错误求助
Let's break down exactly why you're hitting that heap buffer overflow error on LeetCode—your local tests probably didn't cover the edge cases that trigger it, and there are some critical logic flaws in your loop conditions.
The Root Cause of the Overflow
Your while loops are checking the wrong conditions, leading to illegal memory access when accessing arr[k+1] or arr[peek_point+1]:
First loop condition mistake
In this line:while (arr[k] < arr[k+1] && arr[k] < arrSize) {Two big issues here:
- You’re accessing
arr[k+1]before checking ifkis within the valid index range. WhenkreachesarrSize-1(the last valid index),k+1equalsarrSize, which is outside the array’s bounds—accessingarr[k+1]here causes the heap buffer overflow. - The
arr[k] < arrSizecheck is completely irrelevant. This compares the value of the array element to the array’s length, not whether the index is valid. It doesn’t prevent out-of-bounds access at all.
- You’re accessing
Second loop condition mistake
The same problem repeats here:while(arr[peek_point] > arr[peek_point+1] && arr[peek_point] < arrSize) {Again, you access
arr[peek_point+1]without first confirmingpeek_pointis less thanarrSize-1, and thearr[peek_point] < arrSizecheck is meaningless for index validity.
Additional Logic Flaws
Even if you fixed the overflow, your code would fail some test cases:
- If the array is strictly decreasing (e.g.,
[5,4,3,2,1]), your first loop never runs, sopeek_pointstays at 0. The second loop would run, but this isn’t a valid mountain array (no upward slope). - If the array is strictly increasing (e.g.,
[1,2,3,4,5]), your code would setpeek_pointtoarrSize-1, but the second loop doesn’t run—yet your code would return false (which is correct), but the path to get there involves risky memory access.
Fixed Code
Here’s a corrected implementation that addresses all these issues:
bool validMountainArray(int* arr, int arrSize) { // Mountain arrays need at least 3 elements if (arrSize < 3) return false; int k = 0; // Traverse the upward slope until we hit the peak while (k < arrSize - 1 && arr[k] < arr[k+1]) { k++; } // Peak can't be the first or last element (needs both up and down slopes) if (k == 0 || k == arrSize - 1) return false; // Traverse the downward slope until the end of the array while (k < arrSize - 1 && arr[k] > arr[k+1]) { k++; } // If we reached the end, it's a valid mountain return k == arrSize - 1; }
Why Your Local Tests Didn’t Catch This
Local environments (especially stack memory) are often more forgiving of out-of-bounds access—you might be reading memory that’s technically outside your array but still accessible in your program’s stack space. LeetCode’s judge uses strict memory checking that flags these illegal accesses immediately. Additionally, your test case was a perfect mountain array that never triggered the edge case where k reaches arrSize-1 during the upward loop.
内容的提问来源于stack exchange,提问作者ExOster

