Valgrind says that I have a memory leak of 59 bytes in 59 blocks because of my function ft_strdup :
char *ft_strdup(const char *s)
{
char *dup;
int i;
i = 0;
dup = (char *)malloc((ft_strlen(s) + 1) * sizeof(char));
if (!dup)
return (NULL);
while (s[i])
{
dup[i] = s[i];
i++;
}
dup[i] = '\0';
return (dup);
}
But when I change the size of the allocation to :
dup = (char *)malloc(ft_strlen(s) * sizeof(char));
Valgrind shows me this result :
==36929== definitely lost: 0 bytes in 59 blocks
==36929== indirectly lost: 0 bytes in 0 blocks
Why the 59 blocks still shows up instead of 0 blocks since there isn't any bytes lost?
When you change the size of the allocation to:
dup = (char *)malloc(ft_strlen(s) * sizeof(char));
you're overwriting the memory you haven't allocated with a termination \0
character, which is pretty much the source of your problem.
Agree, valgrind could have given the better diagnostic, but it could have given the worse as well.