简体   繁体   English

它在处理字符串时出现分段错误?

[英]I am getting segmentation fault here while it works with strings?

I have written the following replace function which replaces substring inside a big string as follows: 我编写了以下replace函数,该函数将大字符串内的子字符串替换为:

void replace(char *str1, char *str2, int start, int end)
{
    int i,j=0;
    for(i=start; i<end; i++, j++)
        *(str1+i)=*(str2+j);
}

It works fine when I put a string as replace("Move a mountain", "card", 0,4) , but when I declare a string using pointer array like char *list[1]={"Move a mountain"} and pass it to the function as replace(list[0], "card",0,4) , it gives me a segmentation fault. 当我将字符串作为replace("Move a mountain", "card", 0,4) ,它工作正常,但是当我使用char *list[1]={"Move a mountain"}这样的指针数组声明字符串时,并将其传递给函数replace(list[0], "card",0,4) ,它给我一个分段错误。

Not able to figure it out. 无法弄清楚。 Can anybody please explain this to me? 有人可以向我解释一下吗?

The code of function replace looks fine, yet all the ways you call it introduce undefined behaviour: 函数replace的代码看起来不错,但是您调用它的所有方式都会引入未定义的行为:

First, with replace("Move a mountain", "card", 0,4) , you are passing a string literal as argument for str1 , which is modified in replace then. 首先,使用replace("Move a mountain", "card", 0,4)将字符串文字作为str1参数传递,然后在replace进行修改。 Modifying a string literal is undefined behaviour, and if it "works", it is just luck (more bad luck than good luck, actually). 修改字符串文字是不确定的行为,如果“起作用”,那只是运气(实际上,运气比运气还好)。

Second char *list[1]={"Move a mountain"} is similar but introduces another issue: char*list is an array of pointers, and you initialize list[0] to point to string literal ""Move a mountain" . So passing list[0] would again lead to UB due to modifying a string literal. But then you pass list[1] , which is out of bounds and therefore introduces undefined behaviour. Again, everything can happen, segfaulting being just one such possibility. 第二个char *list[1]={"Move a mountain"}类似,但引入了另一个问题: char*list是一个指针数组,您初始化list[0]指向字符串文字""Move a mountain" 。因此,传递list[0]会由于修改字符串文字而再次导致UB;但是随后传递list[1]却超出了范围,因此引入了未定义的行为。 。

Write

char list[] = "Move a mountain"; // copies string literal into a new and modifiable array 
replace(list, "card",0,4)

and it should work better. 而且应该会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM