Search code examples
cpointersfree

free() function doesnt works


i build a program that translate base 10 ti base 2 and base 16:

#include <stdio.h>

int main(void)
{
    int b10, b2, b16;
    scanf("%d", &b10);//getting a number in base 10
    b16 = b10;
    b2 = b10;

    //******print the number in base 2
    int* ba2 = (int*)malloc(b10/2*4);
    int i = 0,j;
    while (b2 > 0){
        ba2[i] = b2 % 2;
        b2=b2 / 2;
        i++;
    }
    for (j = i-1; j >= 0; j--){
        printf("%d", ba2[j]);
    }   
    free(ba2);
    //**************************

    //******print the number in base 16
    printf("\n");
    int* ba16 = (int*)malloc(b10 / 16 * 4);
    i = 0;
    while (b16 > 0){
        ba16[i] = b16 % 16;
        b16 = b16 / 16;
        i++;
    }
    for (j = i - 1; j >= 0; j--){
        if (ba16[j] < 10)
            printf("%d", ba16[j]);
        else
            printf("%c", 'A' + (ba16[j] - 10));
    }
    free(ba16);
    //****************************

    getch();
    return 0;
}

for some reason the program stop at the second free(). when i created a break point the program just stoped when i got to the free, no msg or warning. can someone help me with is?


Solution

  • You are allocating memory as ba10/16 * 4. For input values less that 16, that evaluates to zero. As per malloc documentation, you will either get null pointer or a unique pointer which can be passed to free. But you are assigning values in ba16[0]. Same holds true for input value of 16. you have allocated 4 bytes. But the program goes on to assign ba16[0] and ba16[1], which will corrupt the array. The same problem exists with ba2 as well. I don't know if you tested with input values less than 16 or 2. Hope this helps.