标签:free har 内存泄露 int replace strlen str 替换 memset
使用完释放记得内存free(str),防止内存泄露
char * replace (const char *str, const char *src, const char *dst)
{
const char* pos = str;
int count = 0;
while ((pos = strstr (pos, src))) {
count ++;
pos += strlen(src);
}
size_t result_len = strlen(str) + (strlen(dst) - strlen(src)) * count + 1;
char *result = (char *)malloc(result_len);
memset (result, 0, result_len);
const char *left = str;
const char *right = NULL;
while ((right = strstr(left, src))) {
strncat (result, left, right - left);
strcat (result, dst);
right += strlen(src);
left = right;
}
strcat(result, left);
return result;
}
标签:free har 内存泄露 int replace strlen str 替换 memset
原文地址:https://www.cnblogs.com/wangjian8888/p/10518366.html