7

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?

Tomer Amir
  • 1,515
  • 4
  • 27
  • 54
  • 2
    You're writing past your allocated bounds (you're allocating memory for `len` chars, so the last accessible index is `rev[len-1]` since rev starts at 0). – ccKep Apr 29 '14 at 21:20
  • 3
    Use calloc(len+1, sizeof(char)) – imreal Apr 29 '14 at 21:20

2 Answers2

7

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.

P.P
  • 117,907
  • 20
  • 175
  • 238
0

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

MH_T
  • 1