I’ve been experimenting with C a little bit. I usually use PHP and javascript.
I did “Hello World” and then I typed in this, which I copied from a website somewhere…
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
int intcmp(const void*v1, const void *v2){
return (*(int *)v1 - *(int *)v2);
}
main(){
int arr[MAX], count, key , *ptr;
printf("Enter %d integer values; press enter after each\n", MAX);
for (count = 0; count < MAX; count++)
scanf("%d", &arr[count]);
puts("Press a key to sort the values");
getc(stdin);
qsort(arr, MAX, sizeof(arr[0]), intcmp);
for(count=0; count < MAX; count++)
printf("\narr[%d] = %d.", count, arr[count]);
puts("\nPress a key to continue");
getc(stdin);
printf("Enter a val to search for");
scanf("%d", &key);
ptr = (int * )bsearch(&key, arr, MAX, sizeof(arr[0]), intcmp);
if(ptr != NULL){
int fred = (ptr - arr);
printf("%d found at arr[%d]", key ,fred);
}else{
printf("%d not found", key);
}
}
So far so good. I’m trying to understand what all the stars do, but it’s falling into place (ha ha – falling stars 🙂
However, if I type in a float e.g. 21.45 when it asks me for 20 integers, it rushes through to “Enter a val to search for” having filled the 20 array values with weird numbers.
Have I created some sort of buffer overflow? I realise that input should be checked – but I’m interested to know what I’ve done. Could I use my program to run arbitrary code? (Well, no, not with my knowledge… but could someone?)
If you enter a value such as
21.45the call toscanf("%d")will fail, as it is not anint, and will leave the.45instdin(the21will be extracted as a validint) to be processed again. This causes the loop to re-read this value again and again (as it fails every time). The weird numbers are due to the elements of the array being uninitialised.Check the return value of
scanf()which returns the number of assignments made and if it fails skip whatever is instdin: