Try this 'non-crashing' version of your code, that does overwrite the bounds of the name
array for modest sizes of input string:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
enum {SIZE = 50};
char target_1 = 'Z';
char name[SIZE] = "Help";
char target_2 = 'Z';
static void read(char *s)
{
char buffer[2*SIZE];
int i = 0;
int c;
while ((c = getchar()) != EOF && c != '\n')
buffer[i++] = c;
buffer[i] = '\0';
for (int j = 0; j < i; j++)
s[j] = buffer[j];
}
int main(void)
{
printf("Data-1: %c %s %c\n", target_1, name, target_2);
read(name);
printf("Data-2: %c %s %c\n", target_1, name, target_2);
return(0);
}
Example runs:
$ for len in 48 49 50 51 52 53 54 ; do echo $len; perl -e "print 'a' x $len" | ./bo; done
48
Data-1: Z Help Z
Data-2: Z aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Z
49
Data-1: Z Help Z
Data-2: Z aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Z
50
Data-1: Z Help Z
Data-2: Z aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaZ Z
51
Data-1: Z Help Z
Data-2: a aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Z
52
Data-1: Z Help Z
Data-2: a aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Z
53
Data-1: Z Help Z
Data-2: a aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Z
54
Data-1: Z Help Z
Data-2: a aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Z
$
You can see that the target_1
is at a higher memory address than name
, and that it does get overwritten from an input of size 52 or larger.
When I say 'non-crashing', I mean 'it does not crash for input lines that are long enough to overflow the name
buffer but not so long as to overflow the buffer
buffer' (roughly lengths 50 to 100). Using longer input strings, the program crashes with a segmentation fault, but it is interesting that it crashes after printing the second line of output, rather than during the return from read()
.
140
Data-1: Z Help Z
Data-2: a aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa Z
Segmentation fault: 11
Tested on Mac OS X 10.9.2 Mavericks, with GCC 4.9.0.