I wrote a function that will take a char*
representing a binary number, and add one to that number. I've encountered a very confusing error, which is that the function works fine and dandy when the char*
comes from user input when calling the function (a.k.a. argv[1]
), but gives me a Bus error: 10
when I instead initialize the variable internally and pass it to the same function. I'm not sure what's behind this, so I turn to you guys. Here's my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void addOneBinaryMain(char* strBiNum, int index)
{
if (strBiNum[index] == '0' || index == 0) { //BUS ERROR OCCURS HERE
strBiNum[index] = '1';
return;
} else {
strBiNum[index] = '0';
addOneBinaryMain(strBiNum, index - 1);
}
}
void addOneBinary(char* strBiNum)
{
addOneBinaryMain(strBiNum, strlen(strBiNum)-1);
}
int main(int argc, char* argv[]) {
char* str = argv[1];
char* strZero = "00000000";
int i;
printf("%s\n", str);
printf("%s\n", strZero);
addOneBinary(str);
printf("added one to input string: %s\n", str); //succeeds
addOneBinary(strZero);
printf("added one to internal zero string: %s\n", strZero);
return 0;
}
Following around the error with print statements, it seems that it occurs in the addOneBinaryMain
function (the recursive step), at the point I've marked.