ft_substr: don't allocate too much mem + handle start outside of str

This commit is contained in:
Khaïs COLIN 2024-10-19 18:36:17 +02:00
parent 29f2cc104a
commit 26618f40b1

View file

@ -6,18 +6,39 @@
/* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */ /* By: kcolin <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/17 11:45:52 by kcolin #+# #+# */ /* Created: 2024/10/17 11:45:52 by kcolin #+# #+# */
/* Updated: 2024/10/17 11:58:18 by kcolin ### ########.fr */ /* Updated: 2024/10/19 18:34:36 by kcolin ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
#include "libft.h" #include "libft.h"
#include <stdlib.h> #include <stdlib.h>
static int min(size_t a, size_t b)
{
if (a > b)
return (b);
return (a);
}
char *ft_substr(char const *s, unsigned int start, size_t len) char *ft_substr(char const *s, unsigned int start, size_t len)
{ {
char *out; char *out;
size_t substr_len;
size_t i;
out = malloc(sizeof(char) * len + 1); substr_len = 0;
i = 0;
while (s[i] != '\0')
{
if (i >= start)
substr_len++;
if (i >= start + len)
break ;
i++;
}
if (i < start)
return (ft_calloc(1, sizeof(char)));
out = ft_calloc(min(substr_len + 1, len + 1), sizeof(char));
if (out == NULL) if (out == NULL)
return (NULL); return (NULL);
ft_strlcpy(out, s + start, len + 1); ft_strlcpy(out, s + start, len + 1);
@ -35,5 +56,6 @@ int main(void)
printf("'%s'\n", ft_substr(data, 15, 4)); printf("'%s'\n", ft_substr(data, 15, 4));
printf("'%s'\n", ft_substr(data, 15, 0)); printf("'%s'\n", ft_substr(data, 15, 0));
printf("'%s'\n", ft_substr(data, 20, 20)); printf("'%s'\n", ft_substr(data, 20, 20));
printf("'%s'\n", ft_substr(data, 100, 27));
} }
*/ */