0

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.

limp_chimp
  • 13,475
  • 17
  • 66
  • 105

2 Answers2

1

strZero points at a constant string, that cannot be changed

mikithskegg
  • 806
  • 6
  • 10
  • Even though I didn't type `const char*`? So is the only way around this is to initialize it with `malloc()` and iteratively assign each value? seems like a PITA, but I suppose if it's the only way it works... – limp_chimp Oct 12 '12 at 00:31
  • 1
    Yes, this array can be allocated in a constant section of process, so any attempt to change it is denied by system. Try char strZero[] = "0000" instead – mikithskegg Oct 12 '12 at 00:34
1

strZero is just a point initialized with the address of your literal string "000000". This literal string is stored at a place in the application's ram that is read only (If i remember correctly think it's called static store).

Try declaring a char array on the stack or on the heap and copying strZero to it using strcpy.

Algebra
  • 86
  • 6
  • 1
    You welcome, Btw, I think there is a a bug in your code, when the binary number overflows (trying to add 1 to 111 to get 000) you will get 100 instead. – Algebra Oct 12 '12 at 00:46