Question

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?

Was it helpful?

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.

OTHER TIPS

When you allocate len to that, the index starts from 0 to len - 1 So you must allocate len +1 to it so you can use index len for NULL

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top