You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言二进制加法程序运行崩溃问题排查求助

Fixing Your C Binary Addition Program (Crash & Logic Issues)

Let's figure out why your program is crashing and fix it up properly. I've gone through your code and spotted three critical issues that are causing the crash and incorrect behavior:

1. Buffer Overflow in convertDecToBin

Your binary1 and binary2 arrays are declared as int[30] (valid indexes 0-29), but in convertDecToBin, you're looping for len=30 iterations and writing to binary[i+1]. When i=29, this tries to access binary[30]—way outside the array's bounds. This corrupts stack memory, which almost always leads to a crash.

2. Unsigned Integer Loop Underflow

In addTwoBinary, you used unsigned int i = 20; i >= 0; i--. Unsigned integers can never be negative, so when i hits 0 and you decrement it, it wraps around to UINT_MAX (like 4294967295). This makes the loop run indefinitely, accessing way out-of-bounds array elements until the OS kills the program.

3. Broken Carry Logic

Your original carry calculation was completely off. Carry should be determined by the total sum of the current bits plus the previous carry, not some arbitrary check on tmp. The correct approach is to track carry through each bit, updating it for the next higher bit.


Fixed Full Code

Here's the repaired program with explanations of each change:

#include <stdio.h>

// Converts 0-1 decimal to binary: stores 0 as integer part, followed by fractional bits
void convertDecToBin(double num, int fractional_bits, int binary[]) {
    double tmp = num;
    binary[0] = 0;  // Integer part is 0 since input is 0 <= num < 1
    
    // Only write to fractional bit positions (1 to fractional_bits)
    for (int i = 0; i < fractional_bits; i++) {
        tmp *= 2;
        binary[i + 1] = tmp >= 1;
        if (tmp >= 1) {
            tmp -= 1;
        }
    }
    
    // Initialize unused array slots to 0 to avoid garbage values
    for (int i = fractional_bits + 1; i < 30; i++) {
        binary[i] = 0;
    }
}

// Performs binary addition with proper carry handling
void addTwoBinary(int binary1[], int binary2[], int sum[]) {
    int carry = 0;
    
    // Traverse from least significant fractional bit (index 20) to integer part (index 0)
    for (int i = 20; i >= 0; i--) {
        int total = binary1[i] + binary2[i] + carry;
        sum[i] = total % 2;  // Current bit is remainder when divided by 2
        carry = total / 2;   // Carry is quotient (0 or 1)
    }
    
    // Handle final carry (sum of two <1 numbers can be up to <2, so integer part becomes 1)
    if (carry != 0) {
        sum[0] = 1;
    }
}

// Prints binary number in readable format (integer part . fractional bits)
void PrintBinary(int binary[], int len) {
    printf("%d.", binary[0]);
    for (int i = 1; i < len; i++) {
        printf("%d", binary[i]);
    }
}

int main(void) {
    double num1, num2;
    // Initialize arrays to 0 to avoid uninitialized garbage values
    int binary1[30] = {0}, binary2[30] = {0}, sum[30] = {0};
    
    printf("Enter two decimal numbers between 0 and 1: ");
    scanf("%lf %lf", &num1, &num2);
    
    // Convert to binary with 20 fractional bits (total 21 bits including integer part)
    convertDecToBin(num1, 20, binary1);
    convertDecToBin(num2, 20, binary2);
    
    printf("\nnum1 is ");
    PrintBinary(binary1, 21);
    printf("\nnum2 is ");
    PrintBinary(binary2, 21);
    
    addTwoBinary(binary1, binary2, sum);
    
    printf("\nsum is ");
    PrintBinary(sum, 21);
    return 0;
}

Key Improvements:

  • Eliminated Buffer Overflow: Now convertDecToBin only writes to valid array indexes, based on the number of fractional bits we want (20 in this case).
  • Fixed Loop Termination: Changed unsigned int to int in the addition loop, so it terminates correctly when i reaches -1.
  • Proper Carry Handling: The addition now follows standard binary rules, tracking carry through each bit correctly.
  • Readable Output: Modified PrintBinary to show a decimal point between the integer and fractional parts, making the binary output easier to interpret.
  • Initialized Arrays: Added zero-initialization for arrays to avoid unexpected garbage values.

Example Run:

Enter two decimal numbers between 0 and 1: 0.5 0.25

num1 is 0.10000000000000000000
num2 is 0.01000000000000000000
sum is 0.11000000000000000000

内容的提问来源于stack exchange,提问作者Marco Altieri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 04:19:11