Your code contains quite a few strange errors.
First, x is a pointer to your target buffer. For the reason you make all your copies directly on x , i.e. Everything is copied at the very beginning of the buffer, overwriting previously copied data. It makes no sense. Do you see this? You need to create a highlighted pointer to save the current destination to x and write data to that position (instead of writing to x ).
I see that you edited your code and replaced copying with concatenation. Well ... Although this may solve the problem, it is still a bad design. strcat / strncat functions have no place in good C code. Anyway, your code is still broken, since you are trying to use strcat functions in an uninitialized x buffer. First you need to initialize x as an empty string.
Secondly, there is a more subtle problem with finding a replacement string. At the end of the loop, you continue the search from the next character r=strstr(r+1,str1) , that is, you increase the search position only by 1. I'm not sure if this is what you want.
Consider aaaa as input and the request to replace aa with bc . How many replacements do you want to make in this case? How many occurrences of aa are in aaaa ? 2 or 3? If you want to get bcbc as the result (2 replacements), you should increase r by strlen(str1) , and not by 1.
In fact, in the current implementation, you set p=r+strlen(str1) , but continue to search at position r+1 . This will lead to completely meaningless results with overlapping occurrences of the search string, as in my example. try it
char *str1="aa",*str2="xyz",*text="aaaa",*final; final=result(str1,str2,text);
and see what happens.