I am trying to write a function that returns a pointer copied from the initial function parameter but without withspaces in the beggining and in the end (' ', '\n', '\t').
char *ft_strtrim(char const *s)
{
unsigned char *p;
int start;
int end;
size_t index;
start = 0;
end = ft_strlen(s) - 1;
while (s[start] == '\n' || s[start] == '\t' || s[start] == ' ')
start++;
while (s[end] == '\n' || s[end] == '\t' || s[end] == ' ')
end--;
if (start == 0 && end == ft_strlen(s) - 1)
return ((char*)s);
if (end - start < 0)
return (NULL);
printf("%d\n", end - start);
p = (char*)malloc(sizeof(char) * (end + 1 - start));
index = 0;
while(start <= end)
{
p[index] = s[start];
index++;
start++;
}
p[index] = '\0';
return (p);
}
I want to return NULL when the value of end - start is below 0.Even though in the printf that I used after it to debug the function the value is negative,the function doesn't return NULL and when I compile the code I get segmentation fault.
strlen(s) == 0
,end == -1
, ands[end]
is undefined behavior.ft_strlen
, and what input is being given to this function?while (s[end] == '\n' || s[end] == '\t' || s[end] == ' ') end--;
is UB.(end - start < 0)
can be simplified to(end < start)
. And the only case where this will happen is if the string is empty or all whitespace. And those are precisely the cases where your code causes undefined behavior, because thewhile
loops don't stop when they reach the beginning or end of the string.