I'm trying to convert a decimal number to a binary number using a recursive function that returns a string. The correct string is stored in to numBin, but a segmentation fault is thrown when it is returned to the calling function (or it just crashes the terminal...hard). I cannot for the life of me figure out what is going on here. Please help!
the std::cout in the recursive function was added for debugging.
#include <iostream>
#include <string>
std::string decToBin(int numDec, int binLength, std::string numBin)
{
if (binLength == 0)
{
std::cout << numBin << std::endl;
//Segmentation fault occurs here.
return numBin;
}
elseif (numDec % 2 == 0)
{
numBin = '0' + numBin;
decToBin(numDec/2,binLength-1,numBin);
}
elseif (numDec % 2 == 1)
{
numBin = '1' + numBin2;
decToBin(numDec/2,binLength-1,numBin);
}
}
std::string decToBin(int numDec)
{
//Count how many times the number can be divided by 2
// using integer division to establish the length of the
// binary number. binLength is used in the recursive function
// as an indexer to end recursion and return the completed array.
int binLength = 0, num = numDec;
do
{
num/=2;
binLength++;
}while (num > 0);
//Construct a string for use in the recursive function.
std::string numBin;
return decToBin(numDec, binLength, numBin);
}
std::string decToBin(int numDec, int binLength, std::string numBin)
{
if (binLength == 0)
{
std::cout << numBin << std::endl;
return numBin;
}
//Note: return transfers control back to the caller, so there's no
//need to have an else here.
if (numDec % 2 == 0)
{
numBin = '0' + numBin;
return decToBin(numDec/2,binLength-1,numBin);
}
//Note: If !(numDec % 2 == 0) then the only possibility is numDec % 2 == 1
else
{
numBin = '1' + numBin2;
return decToBin(numDec/2,binLength-1,numBin);
}
}
Try to figure out why.
Besides that, if a function has a return type different than void, it must have a return statement in every possible code path, or the program is invalid (though the compiler may accept it).