The use of malloc() really does not help you here. Many of the problems still exist in the code.
Code:
char* s = malloc(50 * sizeof(char));
"sizeof(char)" is ALWAYS 1, and only 1.
Code:
char* s = malloc(50);
You should also check if the return from malloc() was successful.
Code:
do
// take user input including white space
{
printf("please enter some text no longer than 50 chars:\n");
scanf("%[^\n]",s);
}
// while s is empty or over 50
while ( strlen(s)+1 == 0 || strlen(s)+1 > 50 );
If the user has typed in more than 49 characters, you're too late! You have overwritten memory outside of the allocated memory!
A better solution:
Code:
scanf("%49[^\n]", s);
Or better use fgets().
"strlen(s)+1 == 0" strlen() returns 0 or greater than 0, "strlen(s)+1" will NEVER equal zero!
Code:
if (s != NULL)
{
// print input to screen
printf("\nYou typed:\n");
printf("%s\n",s);
}
You are not checking if someone typed in a string successfully, you are only checking that malloc() returned a valid address of the allocated memory!
I think you need to pick up a good book on C that can fill in the gaps that the course left WIDE open.