【发布时间】:2020-08-18 15:07:47
【问题描述】:
我有一个字符串,我需要在其中找到一个子字符串并替换它。要找到的和将替换它的长度不同。我的部分代码:
char *source_str = "aaa bbb CcCc dddd kkkk xxx yyyy";
char *pattern = "cccc";
char *new_sub_s = "mmmmm4343afdsafd";
char *sub_s1 = strcasestr(source_str, pattern);
printf("sub_s1: %s\r\n", sub_s1);
printf("sub_str before pattern: %s\r\n", sub_s1 - source_str); // Memory corruption
char *new_str = (char *)malloc(strlen(source_str) - strlen(pattern) + strlen(new_sub_s) + 1);
strcat(new_str, '\0');
strcat(new_str, "??? part before pattern ???");
strcat(new_str, new_sub_s);
strcat(new_str, "??? part after pattern ???");
-
为什么会出现内存损坏?
-
如何有效提取
pattern并将new_sub_s替换为new_sub_s?
【问题讨论】:
-
最好先看这里geeksforgeeks.org/…
-
@user3121023 我有这个
strcat(new_str, '\0'); -
@kosmosu 两个问题,
strcat()假设new_str是空终止的,正如 user3121023 指出的那样,malloc()不是这种情况。其次,'\0'是char,而不是char*。
标签: c