Well, I'm doing a "binary converter" in C, and then making a binary calculator as part of a college challenge. I worked out the algorithm the same way we do it by hand, but bizarrely, it can only convert up to 127, when I try to convert 128, I get this log:
0 [main] teste 698 cygwin_exception::open_stackdumpfile: Dumping stack trace to teste.exe.stackdump
The code:
decToBin function -
#define BASE 2
int* decToBin(int decimal){
int rest = 0, ind = 0;
int *bin = (int *) calloc(1, sizeof(int));
while(decimal >= BASE){
rest = decimal % BASE;
bin[ind] = rest;
bin = (int *) realloc(bin, sizeof(int));
ind++;
decimal /= BASE;
}
bin = (int *) realloc(bin, 2*sizeof(int));
bin[ind] = decimal;
bin[++ind] = -1;
return bin;
}
main function -
int main(){
int* binary = decToBin(128);
for(int i = 0; binary[i] != -1; i++){
printf("%d ", binary[i]);
}
return 0;
}
Someone can explain me what is going on?