I'm trying to recreate strstr
in c, my code works but I think it is too long, and it needs some improvement.
#include <stdlib.h>
static int find_str_indx(char *str, int index, char *str_to_find)
{
int i;
int temp;
int found_index;
while (str[index] != '\0')
{
if (str[index] == *str_to_find)
{
temp = index;
i = 0;
found_index = index;
while (str_to_find[i] != '\0' && str[index] != '\0')
{
if(str_to_find[i] != str[index])
found_index = -1;
i++;
index++;
}
if (found_index == -1)
index = temp;
}
index++;
}
return (found_index);
}
char *my_strstr(char *str, char *to_find)
{
char *found_str;
int found_index;
int i;
found_str = (char*)malloc(sizeof(found_str));
found_index = find_str_indx(str, 0, to_find);
if (found_index != -1)
{
i = 0;
while (str[found_index] != '\0')
{
found_str[i] = str[found_index];
found_index++;
i++;
}
}
else
found_str = NULL;
return (found_str);
}
UPDATE
I have rewritten the code to get rid of allocating memory inside strstr
, as advised by ratchet freak
and Jerry Coffin
.
char *my_strstr(const char *haystack, const char *needle)
{
size_t needle_len;
needle_len = strlen(needle);
while (*haystack)
{
if (*haystack == *needle)
{
if (!strncmp(haystack, needle, needle_len))
return ((char *)haystack);
}
haystack++;
}
return (NULL);
}
sizeof(found_str)
is always the size of a pointer (4 or 8 depending on 32 or 64 bit) so it's very likely that you will overflow that buffer. Not to mention strstr shouldn't allocate anything in the first place. You also leak thefound_str
if you didn't find the substring. \$\endgroup\$my_strstr()
document/test its intended/actual functionality with corner cases ofmy_strstr("", "needle")
,my_strstr("haystack", "")
,my_strstr("", "")
. \$\endgroup\$