So, my task is to make and return a copy of a given string, and in case it has failed (for example, hit enter) to return NULL. However, when I hit Enter, the program continues to work and to print out some garbage values. The fun fact though, is that the program works just fine when I run it through the Debugger (which chalenges me the most). I don't find a simple explanation for what might've gone wrong. Or is it the problem with my compiler?
#include <stdio.h>
#include <stdlib.h>
// listing functions
char *ft_strdup(char *src);
int main(void)
{
// input of a string
char c[200];
scanf("%[^\n]%*c", c);
// calling a function
char *f = ft_strdup(c);
printf("\n%s\n", f);
free(f);
return 0;
}
char *ft_strdup(char *src)
{
int i = 0;
// itearting to get the 'length' of string src
while (src[i] != '\0')
++i;
// if user has inputted nothing - return NULL and break the function
if (i == 0)
{
return NULL;
}
// otherwise, make a copy of the string
char *x = malloc(i+1);
int j = 0;
while (j != i)
{
x[j] = src[j];
++j;
}
x[i+1] = '\0';
// print out and return
printf("%s\n%s\n%i", x, src, i);
return x;
}