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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With