Click here to Skip to main content
15,867,835 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wrote this function based on strstr.
If the substring is found, it returns it. But when it's not found, gives me segfault. What should I change?

char	*ft_strstr(char *str, char *to_find)
{
	int	i;
	int	j;

	i = 0;
	j = 0;
	if (to_find[j] == '\0')
		return (str);
	while (str[i] != '\0')
	{
		while (str[i + j] == to_find[j] && str[i + j] != '\0')
			j++;
		if (to_find[j] == '\0')
			return (str + i);
		i++;
		j = 0;
	}
	return (0);
}


What I have tried:

I've changed it many times, but no luck.
Posted
Updated 7-Feb-23 21:53pm
Comments
Andre Oosthuizen 8-Feb-23 4:06am    
Search for string inside another string might help - https://www.codingame.com/playgrounds/14213/how-to-play-with-strings-in-c/search-within-a-string#:~:text=The%20function%20strstr%20returns%20the,a%20substring%20of%20another%20string.
Navid Rigi Ebrahimi 8-Feb-23 4:20am    
great, thanks

1 solution

Look at your code: you have a loop limited to the length of the string, but you access characters beyond that limit:
while (str[i] != '\0')
{
    while (str[i + j] == to_find[j] && str[i + j] != '\0')
Since you increment j without checking if to_find is exhausted, you can go well outside the loop bounds.

Use the debugger to follow exactly what your code is doing while it is running, and you'll see where your problem happens and what your variables contain.
 
Share this answer
 
Comments
CPallini 8-Feb-23 4:21am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900