处理字符串时出现超级奇怪的错误

Super weird error when handling strings

本文关键字:错误 字符串 处理      更新时间:2023-10-16

我正在尝试创建一个将二进制数(字符串)转换为十进制数(整数)的函数。下面代码的奇怪之处在于,当行"//cout <<索引<<endl;"没有被注释掉时,它可以工作!为什么是D:?

注释掉时的输出:

1651929379

激活时的输出:

7 192 程序以退出代码结束:0

这是整个程序:

//
//  testish.cpp
//  Egetskojs
//
//  Created by Axel Kennedal on 2014-02-13.
//  Copyright (c) 2014 Axel Kennedal. All rights reserved.
//
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int BinaryToDecimal(string & binaryString);
int main(){
    string binary = "11000000";
    int decimal = BinaryToDecimal(binary);
    cout << decimal << endl;


    return 0;
}

int BinaryToDecimal(string & binaryString){
    int solution;
    if (binaryString == "0") solution = 0;
    if (binaryString == "1") solution = 1;
    int index = binaryString.length() - 1; //The index of the last (rightmost) bit in the string
    //cout << index << endl;
    int currentBit = 0; //The exponent to be used when calculating the value of a bit
    for (; index >= 0; index--) {
        if (binaryString.at(index) == '1') {
            solution += pow(2, currentBit);
        }
        //Else: nothing happens
        currentBit++;
    }
    //Done!
    return solution;
}
你在

BinaryToDecimal中有未定义的行为,因为变量solution可能在未初始化的情况下使用。

未初始化的局部变量将具有不确定的值(即它们的值似乎是随机的)。

正如 Joachim 所说,您的解决方案变量是未初始化的,因此当字符串既不是"0"也不是"1"时,您可能会在 += 操作中出现奇怪的行为(例如整数溢出)。我猜它在输出处于活动状态时工作的事实是由于输出指令的一些奇怪的副作用导致某些寄存器包含 0,并且该寄存器是 solution 值的来源。了解编译器设置的内容并查看这部分代码的汇编程序代码可能会有所启发。
您可以替换:

int BinaryToDecimal(string & binaryString){
    int solution;
    if (binaryString == "0") solution = 0;
    if (binaryString == "1") solution = 1;
    ...

跟:

int BinaryToDecimal(string & binaryString){
    int solution = 0;
    ...

由于您所做的特殊情况处理由您的循环优雅地处理。