It has already been indicated in comments and in the eferion response that the trigger for your failure is to misuse the scanf
function. I join the advice of the rest of users when recommending that you read the manual of said function; However, knowing where the program fails does not explain why it fails. The explanation is somewhat complex.
The function scanf
is part of the libraries of c and therefore follows the rules of the C language in its operation; One of the limitations of this language is the absence of references 1 and this limitation means that to modify a variable outside its scope it is necessary to pass the memory address of it.
Since you have passed "%i"
as a read format, the scanf
function will wait to write to an integer ( int
) and therefore assumes that it will receive an integer pointer. I insist on the concept that scanf
assumes that it will receive an integer pointer , this function (from the C libraries) has no way to verify that the type of data provided matches the data type expected 2 and therefore assumes that it will be; It is the programmer's job to ensure that this precondition 3 .
In your code, you failed in your responsibility as a programmer to ensure the expected precondition for scanf
, so he assumed that the integer you were passing as a parameter was an integer pointer. In your code we can see that you do not initialize variable dia
, according to C ++ initialization rules this will leave said variable with an indeterminate value and that value will be what scanf
interprets as a memory address that when trying to write in it a segment violation will occur and the operating system will inform you that your program.exe has stopped work .
You can know the difference between pointer and reference in this thread .
In other words: you can not guarantee security of the types .
For these reasons the scanf
function is considered as unsafe, prone to errors and a possible security hole in the system, even if there is tutorials to take advantage of the vulnerabilities caused by the scanf
function. Therefore in C ++ its use is discouraged and in C it is advised to use secure alternatives such as sscanf
(< em> s
ecure scanf
).