The purpose of this program is to determine if a number between 1 and 1000 is prime by testing its divisibility with the first 11 prime integers. The program functions properly with most inputs. However, when I input an integer such as 468, stack smashing is detected. What is stack smashing and how do I resolve the issue?
I've tried researching stack smashing but I can't find specific examples that relate to my program. I am unaware of alternative methods I could try to amend the program as I am relatively new to programming with C.
char divStatement[] = " is divisible by ";
if ((userInput % 31) == 0) {
div31 = true;
strcat(divStatement, "31, ");
}
if (div2 || div3 || div5 || div7 || div11 || div13 || div17 || div19 || div23 || div29 || div31) {
divStatement[strlen(divStatement) - 2] = '.';
divStatement[strlen(divStatement) - 1] = '\n';
printf("%d%s", userInput, divStatement);
printf("%d is not prime.\n", userInput);
}
else {
printf("%d is prime.\n", userInput);
}
The output actually works properly. At the end of the program, however, the terminal outputs:
***stack smashing detected ***: ./a.out terminated
Aborted
char divStatement[] = " is divisible by ";
if ((userInput % 31) == 0) {
div31 = true;
strcat(divStatement, "31, ");
}
divStatement
is a char array exactly large enough to hold " is divisible by "
plus a \0
terminator. You can't append "31, "
to it because it doesn't have any extra slack space.
An easy fix is to give the array an explicit length that's large enough to handle anything your program might append.
char divStatement[1000] = " is divisible by ";