3
I am creating a C script to classify a triangle according to the 3 sides passed. For this I use three distinct variables, lado1
, lado2
and lado3
, as illustrated by the code below:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
unsigned short int lado1, lado2, lado3;
printf("L1: ");
scanf("%i", &lado1);
printf("L2: ");
scanf("%i", &lado2);
printf("L3: ");
scanf("%i", &lado3);
if (lado1 < (lado2 + lado3) && lado2 < (lado1 + lado3) && lado3 < (lado1 + lado2)) {
if ((lado1 == lado2) && (lado2 == lado3)) {
printf("Triângulo equilátero");
} else if ((lado1 != lado2) && (lado2 != lado3)) {
printf("Triângulo escaleno");
} else {
printf("Triângulo isóceles");
}
} else {
printf("Os lados informados não constituem um triângulo");
}
return 0;
}
However, when I try to compile this code a memory error is shown:
stack smashing detected: <unknown> terminated
The same does not happen when I declare a string along with the other three variables lado1
, lado2
and lado3
. Thus, in addition to the three variables I have another variable of type string folk[90]
which is not used within the code at any time, but this time I have the desired return.
Follows the code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
unsigned short int lado1, lado2, lado3, folk[90];
printf("L1: ");
scanf("%i", &lado1);
printf("L2: ");
scanf("%i", &lado2);
printf("L3: ");
scanf("%i", &lado3);
if (lado1 < (lado2 + lado3) && lado2 < (lado1 + lado3) && lado3 < (lado1 + lado2)) {
if ((lado1 == lado2) && (lado2 == lado3)) {
printf("Triângulo equilátero");
} else if ((lado1 != lado2) && (lado2 != lado3)) {
printf("Triângulo escaleno");
} else {
printf("Triângulo isóceles");
}
} else {
printf("Os lados informados não constituem um triângulo");
}
return 0;
}
What I want to know is the explanation for this, why does this occur? and how to allocate memory correctly without needing this fourth variable?
The compiler I use is the gcc
I could not replicate the error. Both codes worked. I passed values 3,4 and 5
– Augusto Vasques
@Augustovasques but which compiler do you use?
– Abel Souza Costa Junior
I used a container with gcc
– Augusto Vasques