I have been given a task at school to write a program that
- Reads three strings
- Stores the third string in dynamically allocated memory
- Print out the last 4 letters of the first word alphabetically.
Here is the program I have so far. The strings are all stored in different variables, making them hard to sort. If anyone could give me a hand and help me finish this program, I would be very grateful.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char word1[101];
char word2[101];
char* word3;
char buffer[101];
scanf("%s", word1);
scanf("%s", word2);
scanf("%s", buffer);
word3 = (char *) malloc(strlen(buffer)+1);
strcpy(word3, buffer);
return 0;
}
scanf( "%s", word )is unsafe. You are asking for a buffer overflow error. Simply enter a string that exceeds 100 characters and BOOM--buffer overflow. Limit the max size of the scan withscanf( "%100s", word ). See en.wikipedia.org/wiki/Scanf#Security for more info.strcpy--this function is the cause of many buffer overflow vulnerabilities. Consider usingstrncpy, which limits the maximum size of the string, instead. Even still, withstrncpythe final character copied is not guaranteed to be\x00, so be sure to set the final character after you copy the data. Losing string terminators can cause major headaches.