Search code examples
carraysmallocfree

"Double free or corruption" error inside this function?


Below is my function. It runs correctly once, then when it is called a second time it causes an error telling me "double free or corruption". I tried adding the +1 inside the malloc() as other posts have suggested, even though I am not storing null-terminated strings but arrays of integers. It did not help.

I am very confused at this point. I don't understand why at the end of the function the pointer that was free()'d doesn't go out of scope, or if it does, then how it can be considered a double-free when I malloc()'d after free()ing it the last time it was used.

int getCount(int number) {

    int totalUniqueDigits = 0;

    bool* allDigits = (bool*)malloc(10 * sizeof(bool));

    do {
        int currentDigit = number % 10;
        number /= 10;
        allDigits[currentDigit] = true;
    } while (number > 0);

    for (int i = 0; i < 10; i += 2) {   
        if (allDigits[i] == true) {     
            totalUniqueDigits++;        
        }
    }

    free(allDigits);    /*This is where the problem is, but only the second time the function is called. */ 
    allDigits = NULL;

    return totalUniqueDigits; 
}

Solution

  • If number is negative, then

    currentDigit = number % 10;
    

    will be negative also (or zero if divisible by 10). This is a somewhat awkward (IMO) definition of the modulus operator.

    If currentDigit is negative, then

    allDigits[currentDigit] = true;
    

    will write out of bounds. On most systems, writing to allDigits[-1] would overwrite information used to manage memory. This might not directly crash your program, but using malloc later could have that effect.

    The solution of course is to either use abs or add 10 to currentDigit if it is negative.