【发布时间】:2015-09-27 22:11:55
【问题描述】:
现在,我正在尝试通过编写一个函数来熟悉 C,给定一个字符串,该函数将用新的子字符串替换目标子字符串的所有实例。但是,我遇到了重新分配 char* 数组的问题。在我看来,似乎我能够在主循环结束时成功地将数组string 重新分配到所需的新大小,然后执行strcpy 以用更新的字符串填充它。但是,在以下情况下它会失败:
字符串的原始输入:“使用洗手间。然后我需要”
要替换的目标:“the”(不区分大小写)
期望的替换值:“th'”
在循环结束时,printf("result: %s\n ",string); 行打印出正确的短语“use th' restroom. Then I need”。但是,string 似乎随后会自行重置:在while() 语句中对strcasestr 的调用成功,循环开头的行printf("string: %s \n",string); 打印原始输入字符串,并且循环无限期地继续。
任何想法都将不胜感激(我提前为我的调试printf 语句道歉)。谢谢!
函数代码如下:
int replaceSubstring(char *string, int strLen, char*oldSubstring,
int oldSublen, char*newSubstring, int newSublen )
{
printf("Starting replace\n");
char* strLoc;
while((strLoc = strcasestr(string, oldSubstring)) != NULL )
{
printf("string: %s \n",string);
printf("%d",newSublen);
char *newBuf = (char *) malloc((size_t)(strLen +
(newSublen - oldSublen)));
printf("got newbuf\n");
int stringIndex = 0;
int newBufIndex = 0;
char c;
while(true)
{
if(stringIndex > 500)
break;
if(&string[stringIndex] == strLoc)
{
int j;
for(j=0; j < newSublen; j++)
{
printf("new index: %d %c --> %c\n",
j+newBufIndex, newBuf[newBufIndex+j], newSubstring[j]);
newBuf[newBufIndex+j] = newSubstring[j];
}
stringIndex += oldSublen;
newBufIndex += newSublen;
}
else
{
printf("old index: %d %c --> %c\n", stringIndex,
newBuf[newBufIndex], string[stringIndex]);
newBuf[newBufIndex] = string[stringIndex];
if(string[stringIndex] == '\0')
break;
newBufIndex++;
stringIndex++;
}
}
int length = (size_t)(strLen + (newSublen - oldSublen));
string = (char*)realloc(string,
(size_t)(strLen + (newSublen - oldSublen)));
strcpy(string, newBuf);
printf("result: %s\n ",string);
free(newBuf);
}
printf("end result: %s ",string);
}
【问题讨论】:
-
代码中的每一次强制转换都是多余的和/或引入错误;把它们拿出来
-
为了改善您的问题,发布MCVE 显示使用导致问题的参数调用此函数,并显示您获得的输出。例如,也许您为
strLen参数传递了错误的值,我们无法从这个 sn-p 中分辨出来。 -
你没有为空终止符分配足够的内存
-
strcasestr无论如何都会忽略strLen所以如果你的目标是处理计数字符串,这个函数不会实现它。如果您的目标是处理以空字符结尾的字符串,那么它会引入额外的失败点,要求调用者也传递正确的长度;该函数应根据需要调用strlen。 -
这个函数在
realloc之后永远不会对string做任何事情:你做了printf("end result: %s ",string);但永远不会把它返回给调用者或任何东西。我希望调用代码不会尝试重新使用您作为第一个参数传入的指针...(该内存块已被 realloc 调用释放)。
标签: c arrays regex string malloc