Search code examples
cfreecalloc

"Heap corruption detected" when using free()


I'm pretty new to C (it's actually my first assignment with pointers), and I cant figure out this bug...

here is my code:

void str_rv(char c[]) {
    int i, len = str_ln(c);
    char *rev = (char*)calloc(len, sizeof(char));

    check_mem(rev);

    for (i = 0; i < len; ++i) {
        rev[i] = c[len - (i + 1)];
    }

    rev[len] = '\0';
    str_cpy(rev, c);

    printf("Current string is ");
    str_print(c);
    putchar('\n');
    free(rev);
}

In this function, I'm trying to reverse a string that I got from sacnf(). when i debugged it, it ran fine, until the last line where I use free(). I read a bit online, and I'm sure it's the only place where I try to rfee this memory.

Help?


Solution

  • You are overwriting beyond the bounds of array here:

    rev[len] = '\0';
    

    You have allocated only len chars. Instead you can allocate len +1 chars.

    Thus causing undefined behaviour. This probably resulted the corruption of meta data which results in free()'s failure.

    Also, don't cast the return of malloc()/calloc() etc. You should also check whether calloc() succeeded.