-3

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?

motorola
  • 121
  • 5

2 Answers2

2

You never allocate space for more than one integer for bin, yet you try to store more than one integer there.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • ok, i understand what is happening in the code now, but would you explain to me why the algorithm works up to 127? – motorola Aug 23 '19 at 22:48
  • @motorola Undefined behavior is undefined. See also http://c-faq.com/malloc/badalloc.html and http://c-faq.com/malloc/badalloc2.html. – melpomene Aug 23 '19 at 22:52
  • @motorola It doesn't really work up to 127. Generally, we describe code as working when it does what we expect it to do. Looking at the code, I'd expect it to crash or go awry after two or three bytes. It doesn't do that. So it really doesn't work up to 127. If you mean why does it do what you wanted it to do up to 127, it's because there are no rules that require it to do any particular thing. – David Schwartz Aug 23 '19 at 22:52
0

Welcome to C programming

realloc manual: The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes

Your code: bin = (int *) realloc(bin, sizeof(int));

So this line is reallocating 4 bytes to 'bin' every time. It should grow it by 4 bytes on each iteration like this I guess: bin = (int *) realloc(bin, ++ind * sizeof(int));

and then don't increment on the next line.

As to the program crashing on 127, what you are seeing is common in C/C++ due to the fact there is no bounds checking on array accesses. It should crash on a input of 2 but isn't due to randomness about how your code is compiled as well as details about how alloc works (alloc typically will give a larger block than asked for if you ask for something too small or not a power of 2.)

STL solves these kinds of problems.

Fracdroid
  • 1,135
  • 10
  • 15