Skip to content

Add binary search implementation in C#124

Merged
x0lg0n merged 1 commit intox0lg0n:mainfrom
janvi100104:feature/c
Oct 27, 2025
Merged

Add binary search implementation in C#124
x0lg0n merged 1 commit intox0lg0n:mainfrom
janvi100104:feature/c

Conversation

@janvi100104
Copy link
Contributor

@janvi100104 janvi100104 commented Oct 27, 2025

Add binary search implementation in C

Summary by Sourcery

New Features:

  • Implement an iterative binary search function in C with a command-line interface for user input and output.

Summary by CodeRabbit

New Features

  • Added binary search tool that allows users to search sorted integer arrays with clear feedback on search results.

@sourcery-ai
Copy link
Contributor

sourcery-ai bot commented Oct 27, 2025

Reviewer's Guide

Adds a standalone iterative binary search utility in C, complete with command-line prompts, input validation, dynamic memory management, and result reporting.

Class diagram for binary search implementation in C

classDiagram
    class binary_search {
        +int binary_search(int arr[], int n, int target)
    }
    class main {
        +int main(void)
    }
    main --> binary_search : calls
Loading

File-Level Changes

Change Details Files
Implement iterative binary search algorithm.
  • Initialize lower and upper bounds.
  • Compute mid index safely to avoid overflow.
  • Compare mid element to target and adjust bounds.
  • Return index if found or -1 otherwise.
C/binarySearch.c
Add main function for user interaction, input handling, and memory management.
  • Prompt for and validate number of elements.
  • Allocate array dynamically and handle allocation failure.
  • Read sorted integers with per-element validation.
  • Prompt for and validate target value.
  • Invoke binary_search and print found/not found message.
  • Free allocated memory before exit.
C/binarySearch.c

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai
Copy link

coderabbitai bot commented Oct 27, 2025

Walkthrough

A new C file implementing an iterative binary search algorithm is added. The implementation includes a binary_search function that searches a sorted integer array and a main function handling user input for array size, elements, and target value lookup with basic error handling and memory management.

Changes

Cohort / File(s) Summary
New binary search implementation
C/binarySearch.c
Added iterative binary search function and interactive main program with array initialization, input validation, memory allocation, and result reporting

Sequence Diagram

sequenceDiagram
    participant User
    participant Program
    participant Memory

    User->>Program: Enter array size
    Program->>Program: Validate size > 0
    Program->>Memory: Allocate array
    Memory-->>Program: Memory allocated
    
    loop For each element
        User->>Program: Enter sorted integer
        Program->>Memory: Store in array
    end
    
    User->>Program: Enter target value
    Program->>Program: binary_search(array, size, target)
    Program->>Program: Compare mid element
    alt Found
        Program->>User: Return index
    else Not found
        Program->>User: Return -1
    end
    
    Program->>Memory: Free array
    Memory-->>Program: Freed
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

  • Area of attention: Verify binary search logic correctly implements mid-point calculation and boundary conditions
  • Area of attention: Confirm input validation and error handling cover edge cases (negative size, read failures, null pointer)
  • Area of attention: Check memory is properly freed in all code paths

Poem

🐰 A search through the sorted and swift,
Finding needles with logarithmic gift,
Binary hops left and right,
Each step brings clarity and light,
Data divided, no more to drift! 🔍

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "Add binary search implementation in C" directly and accurately describes the main change in the changeset. The pull request introduces a new C file with a binary search algorithm implementation, which is exactly what the title conveys. The title is concise, clear, and specific enough that a teammate reviewing repository history would immediately understand the primary purpose of this change. It avoids vague language and noise, and appropriately summarizes the key contribution without attempting to cover implementation details like the interactive I/O or error handling that are secondary to the core objective.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@qodo-code-review
Copy link

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
Untrusted input assumptions

Description: The program trusts that the provided array is sorted ascending as instructed but does not
verify sorting, allowing a malicious or mistaken input to yield misleading results; if
used in broader contexts, this could be abused to induce incorrect logic decisions.
binarySearch.c [25-59]

Referred Code
if (printf("Enter number of elements: ") < 0) return 1;
if (scanf("%d", &n) != 1 || n <= 0) {
    fprintf(stderr, "Invalid number of elements.\n");
    return 1;
}

int *arr = malloc(sizeof(int) * n);
if (!arr) {
    fprintf(stderr, "Memory allocation failed.\n");
    return 1;
}

printf("Enter %d sorted integers (ascending) separated by spaces or newlines:\n", n);
for (int i = 0; i < n; ++i) {
    if (scanf("%d", &arr[i]) != 1) {
        fprintf(stderr, "Failed to read array element %d.\n", i);
        free(arr);
        return 1;
    }
}



 ... (clipped 14 lines)
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status: Passed

Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
No audit logs: The program performs input processing and memory allocation without emitting any audit
logs of critical actions, which may be acceptable for a CLI demo but lacks audit trail
coverage.

Referred Code
int *arr = malloc(sizeof(int) * n);
if (!arr) {
    fprintf(stderr, "Memory allocation failed.\n");
    return 1;
}

printf("Enter %d sorted integers (ascending) separated by spaces or newlines:\n", n);
for (int i = 0; i < n; ++i) {
    if (scanf("%d", &arr[i]) != 1) {
        fprintf(stderr, "Failed to read array element %d.\n", i);
        free(arr);
        return 1;
    }
}

int target;
if (printf("Enter value to search: ") < 0) { free(arr); return 1; }
if (scanf("%d", &target) != 1) {
    fprintf(stderr, "Failed to read target value.\n");
    free(arr);
    return 1;


 ... (clipped 11 lines)
Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Input edge cases: While errors are handled with messages, the code assumes the array is sorted and does not
handle potential integer overflow in midpoint or extremely large n beyond practical
limits.

Referred Code
    int lo = 0;
    int hi = n - 1;
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;
        if (arr[mid] == target) return mid; // found
        else if (arr[mid] < target) lo = mid + 1;
        else hi = mid - 1;
    }
    return -1; // not found
}

int main(void) {
    int n;
    if (printf("Enter number of elements: ") < 0) return 1;
    if (scanf("%d", &n) != 1 || n <= 0) {
        fprintf(stderr, "Invalid number of elements.\n");
        return 1;
    }

    int *arr = malloc(sizeof(int) * n);
    if (!arr) {


 ... (clipped 17 lines)
Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Limited validation: The program validates numeric reads and n>0 but does not constrain n size or handle
non-sorted input which may lead to incorrect behavior rather than a secure rejection.

Referred Code
if (scanf("%d", &n) != 1 || n <= 0) {
    fprintf(stderr, "Invalid number of elements.\n");
    return 1;
}

int *arr = malloc(sizeof(int) * n);
if (!arr) {
    fprintf(stderr, "Memory allocation failed.\n");
    return 1;
}

printf("Enter %d sorted integers (ascending) separated by spaces or newlines:\n", n);
for (int i = 0; i < n; ++i) {
    if (scanf("%d", &arr[i]) != 1) {
        fprintf(stderr, "Failed to read array element %d.\n", i);
        free(arr);
        return 1;
    }
}
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes and they look great!

Blocking issues:

  • Avoid using 'scanf()'. This function, when used improperly, does not consider buffer boundaries and can lead to buffer overflows. Use 'fgets()' instead for reading input. (link)
  • Avoid using 'scanf()'. This function, when used improperly, does not consider buffer boundaries and can lead to buffer overflows. Use 'fgets()' instead for reading input. (link)
  • Avoid using 'scanf()'. This function, when used improperly, does not consider buffer boundaries and can lead to buffer overflows. Use 'fgets()' instead for reading input. (link)
Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location> `C/binarySearch.c:25` </location>
<code_context>
+
+int main(void) {
+    int n;
+    if (printf("Enter number of elements: ") < 0) return 1;
+    if (scanf("%d", &n) != 1 || n <= 0) {
+        fprintf(stderr, "Invalid number of elements.\n");
</code_context>

<issue_to_address>
**suggestion:** Error handling for printf is rarely necessary.

Consider removing the printf return value check to streamline the code, as output errors are highly unlikely in this context.

```suggestion
    printf("Enter number of elements: ");
```
</issue_to_address>

### Comment 2
<location> `C/binarySearch.c:26` </location>
<code_context>
    if (scanf("%d", &n) != 1 || n <= 0) {
</code_context>

<issue_to_address>
**security (c.lang.security.insecure-use-scanf-fn):** Avoid using 'scanf()'. This function, when used improperly, does not consider buffer boundaries and can lead to buffer overflows. Use 'fgets()' instead for reading input.

*Source: opengrep*
</issue_to_address>

### Comment 3
<location> `C/binarySearch.c:39` </location>
<code_context>
        if (scanf("%d", &arr[i]) != 1) {
</code_context>

<issue_to_address>
**security (c.lang.security.insecure-use-scanf-fn):** Avoid using 'scanf()'. This function, when used improperly, does not consider buffer boundaries and can lead to buffer overflows. Use 'fgets()' instead for reading input.

*Source: opengrep*
</issue_to_address>

### Comment 4
<location> `C/binarySearch.c:48` </location>
<code_context>
    if (scanf("%d", &target) != 1) {
</code_context>

<issue_to_address>
**security (c.lang.security.insecure-use-scanf-fn):** Avoid using 'scanf()'. This function, when used improperly, does not consider buffer boundaries and can lead to buffer overflows. Use 'fgets()' instead for reading input.

*Source: opengrep*
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.


int main(void) {
int n;
if (printf("Enter number of elements: ") < 0) return 1;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Error handling for printf is rarely necessary.

Consider removing the printf return value check to streamline the code, as output errors are highly unlikely in this context.

Suggested change
if (printf("Enter number of elements: ") < 0) return 1;
printf("Enter number of elements: ");

@qodo-code-review
Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
Security
Prevent integer overflow in memory allocation

Add a check before malloc to prevent an integer overflow when calculating the
memory size, which could lead to a heap buffer overflow.

C/binarySearch.c [31]

+if (n > SIZE_MAX / sizeof(int)) {
+    fprintf(stderr, "Array size is too large.\n");
+    return 1;
+}
 int *arr = malloc(sizeof(int) * n);
  • Apply / Chat
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a potential integer overflow vulnerability that could lead to a heap buffer overflow, which is a critical security issue.

High
Possible issue
Validate that the input array is sorted

Add a validation loop to ensure the user-provided array is sorted, as required
by the binary search algorithm, to prevent incorrect results.

C/binarySearch.c [38-44]

 for (int i = 0; i < n; ++i) {
     if (scanf("%d", &arr[i]) != 1) {
         fprintf(stderr, "Failed to read array element %d.\n", i);
         free(arr);
         return 1;
     }
 }
 
+for (int i = 0; i < n - 1; ++i) {
+    if (arr[i] > arr[i + 1]) {
+        fprintf(stderr, "Error: The input array is not sorted.\n");
+        free(arr);
+        return 1;
+    }
+}
+
  • Apply / Chat
Suggestion importance[1-10]: 6

__

Why: The suggestion correctly points out that the program doesn't validate a key precondition (sorted array), which can lead to incorrect results, and proposes a valid check to improve robustness.

Low
  • More

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
C/binarySearch.c (2)

31-35: Memory allocation properly checked.

Good practice checking for allocation failure. The implementation handles errors correctly.

For pedantic safety, consider using size_t for array sizes and checking for potential overflow in the multiplication:

-    int n;
+    size_t n;
     if (printf("Enter number of elements: ") < 0) return 1;
-    if (scanf("%d", &n) != 1 || n <= 0) {
+    if (scanf("%zu", &n) != 1 || n == 0) {
         fprintf(stderr, "Invalid number of elements.\n");
         return 1;
     }
 
-    int *arr = malloc(sizeof(int) * n);
+    if (n > SIZE_MAX / sizeof(int)) {
+        fprintf(stderr, "Array size too large.\n");
+        return 1;
+    }
+    int *arr = malloc(sizeof(int) * n);

37-44: Excellent error handling and resource management.

The array input loop correctly validates each scanf call and properly frees allocated memory on error paths, preventing memory leaks.

Consider adding a brief comment reminding maintainers that the implementation assumes the user provides sorted input (as stated in the prompt):

     printf("Enter %d sorted integers (ascending) separated by spaces or newlines:\n", n);
+    // Note: Binary search requires sorted input; no runtime validation performed
     for (int i = 0; i < n; ++i) {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e25c116 and 7efeaa5.

📒 Files selected for processing (1)
  • C/binarySearch.c (1 hunks)
🧰 Additional context used
🪛 Clang (14.0.6)
C/binarySearch.c

[error] 8-8: 'stdio.h' file not found

(clang-diagnostic-error)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (5)
C/binarySearch.c (5)

11-21: LGTM! Clean binary search implementation.

The binary search algorithm is correctly implemented with proper overflow-safe midpoint calculation using lo + (hi - lo) / 2. The logic is clear and handles all cases correctly.


23-29: Good input validation and error handling.

The validation for the number of elements is thorough, checking both the scanf return value and ensuring n > 0. Error messages are appropriately directed to stderr.


46-52: Consistent and thorough error handling.

Target value input follows the same robust error handling pattern, ensuring allocated memory is freed on all error paths.


54-59: Clear and correct result handling.

The search result is properly interpreted and user-friendly messages are displayed for both success and failure cases.


61-62: Proper resource cleanup.

Memory is correctly freed before successful program exit, completing the robust resource management throughout the program.

@x0lg0n x0lg0n merged commit 220d1e0 into x0lg0n:main Oct 27, 2025
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants