C-Plus-Plus icon indicating copy to clipboard operation
C-Plus-Plus copied to clipboard

Resolved Issue #2939

Open avibega23 opened this issue 5 months ago • 1 comments

  1. Input Validation in main() function: Issue: The original code did not check for non-positive values of n (array size). As a result, entering a value of n <= 0 would cause buffer overflow or undefined behavior when the array was accessed.

Change: Added input validation for the array size n to ensure it is positive. If n <= 0, the program prints an error message and terminates gracefully:

if (n <= 0) { std::cerr << "Error: Array size must be a positive integer.\n"; return 1; }

  1. Handling Empty Arrays in median_of_medians() function: Issue: In the original code, if the array was empty or the median vector m ended up being empty, the program would try to access m[0], causing a buffer overflow.

Change: Before accessing m[(sz - 1) / 2], a check was added to ensure that the median vector m is not empty. If the vector is empty, an error message is printed, and the program exits:

if (m.empty()) { std::cerr << "Error: Median vector is empty.\n"; exit(1); }

  1. Graceful Error Handling for Invalid Inputs: Issue: The code previously did not handle invalid inputs properly, and it would crash with a segmentation fault when invalid input was given.

Change: Instead of continuing with invalid or empty inputs, the program now handles such inputs gracefully by printing error messages and terminating cleanly, thus preventing crashes and undefined behavior.

Example: If n <= 0 is entered, the program prints:

"Error: Array size must be a positive integer."

  1. Edge Case Handling in Test Cases: Issue: The original test cases did not cover edge cases like empty arrays or non-positive sizes.

Change: Though not explicitly mentioned in the test section, handling of invalid inputs was prioritized in the main function, ensuring no test cases would be executed for invalid inputs.

avibega23 avatar Apr 29 '25 09:04 avibega23