Originally Posted by
Andersonsacanno
[code]
std10093 You had mentioned earlier about trusting a user. I'm guessing your talking about a flaw I have in this. Although this is simple I would like to start implementing security features early on. Any advice on improvement is appreciated.
You let the user input the size of spots.If the user inputs a negative or zero number,then you will set the number of spots to a negative or zero number , which does not make any sense. Remember that he may by accident input that number.It would be nice to inform him.In addition inform him that no sorting is going to take place.
You do not have a security issue here, but in general you should always check if the input is satisfying some requirements.Consider this example.We have an array of ten elements and we want the user to input a number, so that we access the element in this specific index.
Code:
#include <stdio.h>
int main(void)
{
int a[5];
int i;
int request;
for( i = 0 ; i < 5 ; i++)
{
a[i] = 7;
}
printf("Please type the number of element you want to access.Indexing starts from zero\n");
scanf("%d",&request);
printf("Element in index %d is %d \n",request,a[request]);
return 0;
}
What will happen if by accident or for other reason i type -1?You are going to access the -1-th element of array a, in other words a[-1], which of course is an error.
So, modify the code to this :
Code:
#include <stdio.h>
int main(void)
{
int a[5];
int i;
int request;
for( i = 0 ; i < 5 ; i++)
{
a[i] = 7;
}
do{
printf("Please type the number of element you want to access.Indexing starts from zero\nNotice that input must be a positive, non-zero number\n");
scanf("%d",&request);
}while(request<=0);
printf("Element in index %d is %d \n",request,a[request]);
return 0;
}
But what if the user inputs an index greater than the index of last element(in this case 4) ?Again, an error is likely to occur .
Again modify the code to this
Code:
#include <stdio.h>
int main(void)
{
int a[5];
int i;
int request;
for( i = 0 ; i < 5 ; i++)
{
a[i] = 7;
}
do{
printf("Please type the number of element you want to access.\n");
printf("Input must be in range of 0 to 4.\n");
scanf("%d",&request);
}while(request<=0 || request>4);
printf("Element in index %d is %d \n",request,a[request]);
return 0;
}
PS - i am telling you from the start that this is not selection sort.Adak also states that.
The do while loop will force the user to input again, if "wrong" input is given.