TheAlgorithms/C-Plus-Plus

[BUG]Buffer overflow in median_search.cpp due to missing input validation in search/median_search.cpp

Closed this issue · 7 comments

Description

A buffer overflow vulnerability exists in median_search.cpp when handling empty or invalid input arrays. The error occurs at:

median_search.cpp:79:11: error: buffer overflow, pointer '&m' accesses 0 bytes at offset 0 bytes of local variable 'm' of size 0 bytes
pivot = m[(sz- 1) / 2

The code fails to validate input size n in main(), allowing zero/negative values
When empty arrays are processed, the median vector m becomes empty
Attempting to access m[0] when m.size() == 0 causes buffer overflow

Expected behavior

Input Validation
The program should validate all user inputs (array size n and elements) and:
Reject non-positive array sizes (n ≤ 0) with a clear error message.
Handle empty arrays gracefully (e.g., throw an exception or return an error code).
Graceful Error Handling
For invalid inputs (e.g., n = 0 or negative sizes):
Display a user-friendly error (e.g., "Error: Array size must be a positive integer").

Actual behavior

Crash on Invalid Input

When entering n ≤ 0 (e.g., 0 or -5), the program crashes with a buffer overflow

Steps to reproduce

No response

Context

Blocked Proper Testing
While implementing unit tests for edge cases, the crashes on empty/negative inputs prevented me from completing test coverage. The code "works" for normal inputs but fails catastrophically for invalid ones.

Additional information

No response

Can You Please Assign It To Me I can Fix It..

Is it resolved or can I work on it?

Is it resolved or can I work on it?

I have Solved it and opened a pull request but not approved yet

Can I work on this?

This issue has been automatically marked as abandoned because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Please ping one of the maintainers once you add more information and updates here. If this is not the case and you need some help, feel free to ask for help in our Gitter channel or our Discord server. Thank you for your contributions!