You've never allocated space for the pointer motf
in function MotMiniscule
:
strcpy(motf,motm);
This is undefined behavior because the address in motf
is indeterminate. You should give it some space to point to:
motf = malloc(100);
The full code should be:
char* MotMiniscule(char* mot)
{
char motm[100],c,*motf;
int i=0;
strcpy(motm,mot);
c=motm[i];
while(c!='\0')
{
printf("%c \n",c);
motm[i]=tolower(c);
i++;
c=motm[i];
}
motf = malloc(100); // Allocate some memory
strcpy(motf,motm);
printf("%s\n",motf);
return(motf);
}
int main()
{
char *mot="HEllooOoMA",*min;
min=MotMiniscule(mot);
printf("\n le mot est %s:\n",mot);
printf("|| %s ||",min);
free(min); // Don't forget to free dynamically allocated memory
}
As pointed out by John Bode, the use of motm
is totally redundant. You can safely remove it. Besides, the size of the dymanical allocation should rely on the length of mod
. So a refined version of the code is this.
char* MotMiniscule(char* mot)
{
char c, *motf;
int i = 0;
c = mot[0];
motf = malloc(strlen(mot) + 1); // Allocate some memory
while (c != '\0')
{
printf("%c\n", c);
motf[i] = tolower(c);
i++;
c = mot[i];
}
// No need to copy again, but
motf[i] = '\0'; // Remember to terminate it
printf("%s\n", motf);
return(motf);
}
int main()
{
char *mot = "HEllooOoMA", *min;
min = MotMiniscule(mot);
printf("\n le mot est %s:\n", mot);
printf("|| %s ||", min);
free(min); // Remember to free it
}