Why am I getting a double free or corruption error with realloc()?

I've tried to write a string replace function in C, which works on a `char *`, which has been allocated using `malloc()`. It's a little different in that it will find and replace strings, rather than characters in the starting string. It's trivial to do if the search and replace strings are the same length (or the replace string is shorter than the search string), since I have enough space allocated. If I try to use `realloc()`, I get an error that tells me I am doing a double free - which I don't see how I am, since I am only using `realloc()`. Perhaps a little code will help: void strrep(char *input, char *search, char *replace) { int searchLen = strlen(search); int replaceLen = strlen(replace); int delta = replaceLen - searchLen; char *find = input; while (find = strstr(find, search)) { if (delta > 0) { realloc(input, strlen(input) + delta); find = strstr(input, search); } memmove(find + replaceLen, find + searchLen, strlen(input) - (find - input)); memmove(find, replace, replaceLen); } } The program works, until I try to `realloc()` in an instance where the replaced string will be longer than the initial string. (It still kind of works, it just spits out errors as well as the result). If it helps, the calling code looks like: #include #include #include void strrep(char *input, char *search, char *replace); int main(void) { char *input = malloc(81); while ((fgets(input, 81, stdin)) != NULL) { strrep(input, "Noel", "Christmas"); } }

以上就是Why am I getting a double free or corruption error with realloc()?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » CSS3 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏