From 26618f40b1f3fa0996dd6f0f491a1798c3e7e081 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kha=C3=AFs=20COLIN?= Date: Sat, 19 Oct 2024 18:36:17 +0200 Subject: [PATCH] ft_substr: don't allocate too much mem + handle start outside of str --- ft_substr.c | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/ft_substr.c b/ft_substr.c index cce6997..155f423 100644 --- a/ft_substr.c +++ b/ft_substr.c @@ -6,18 +6,39 @@ /* 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 +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 *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) return (NULL); 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, 0)); printf("'%s'\n", ft_substr(data, 20, 20)); + printf("'%s'\n", ft_substr(data, 100, 27)); } */