Author:
mkyong
Jul
19

Loading ...
Here i shared a simple method to calculate program execute time or time elapsed in C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| /*calculate program execute time */
#include <time.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
time_t start, stop;
clock_t ticks; long count;
time(&start);
// Do stuff
int i=0;
while(i<50000)
{
printf("Work work %d\n", i);
i++;
ticks = clock();
}
time(&stop);
printf("Used %0.2f seconds of CPU time. \n", (double)ticks/CLOCKS_PER_SEC);
printf("Finished in about %.0f seconds. \n", difftime(stop, start));
return 0;
} |
Author:
mkyong
Jul
17

Loading ...
Here i shared two basic methods to handle user input in C.
1) scanf - this method is easy get attack by buffer overflow, try input some characters more than what you declare to experience buffer overflow
1
2
3
4
5
6
7
8
9
10
11
| #include <stdio.h>
#include <stdlib.h>
int main()
{
char bStr[80];
printf("\nEnter a very very very long String value:");
scanf("%s", bStr);
printf("\nLong String value:%s \n\n",bStr);
return 0;
} |
2) fgets - this method can protect buffer overflow by limit the character user input
1
2
3
4
5
6
7
8
9
10
11
| #include <stdio.h>
#include <stdlib.h>
int main()
{
char bStr[80];
printf("\nEnter a very very very long String value:");
fgets ( bStr, 80, stdin );
printf("\nLong String value:%s \n\n",bStr);
return 0;
} |
However above two methods only can handle normal user input, how about i want to handle user input with 1000 or even more characters? Yes we can declare like “char bStr[1000]” or even more larger size, but this is not so dynamic and flexible enough. However we can use dynamic memory management in C to solve above problem, we can dynamic increase memory size with realloc() function.
First let see what above scanf() buffer overflow look like, just input more than what you declare and see the result below.

Buffer Overflow is not what we want. Here i share a dynamic memory allocation(realloc) in C to handle user input in unknown size.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| #include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned int len_max = 128;
unsigned int current_size = 0;
char *pStr = malloc(len_max);
current_size = len_max;
printf("\nEnter a very very very long String value:");
if(pStr != NULL)
{
int c = EOF;
unsigned int i =0;
//accept user input until hit enter or end of file
while (( c = getchar() ) != '\n' && c != EOF)
{
pStr[i++]=(char)c;
//if i reached maximize size then realloc size
if(i == current_size)
{
current_size = i+len_max;
pStr = realloc(pStr, current_size);
}
}
pStr[i] = '\0';
printf("\nLong String value:%s \n\n",pStr);
//free it
free(pStr);
pStr = NULL;
}
return 0;
} |

Done, now this program can handle unknown size user input.