[Courses] [C] issues with gets() (was interesting compiler output)

Andrew Edgecombe andrew.edgecombe at spheresystems.com.au
Fri Dec 13 14:11:16 EST 2002


The main problem with gets() is that there is no way of telling it how
long the buffer is that you're passing it.
This means that a user (either accidentally or maliciously) can overflow
whatever buffer you provide (ie. keep writing valid stuff longer than
the buffer you provide).
When a buffer is overflowed, it means that some other piece of memory is
going to end up with the partial contents of your string, causing at
best strange behaviour.

This can result in intermittent faults, your program stopping dead (with
a SEGFAULT), or the opening up of some soft of vulnerability.
(Of the top of my head, I can't think of a good link to point you at to
describe buffer overflow attacks. I required, I'm sure that I or others
could come up with one though)

A much better function to use is fgets(), which does allow you to
specify a maximum length for your buffer.

As a practical example of the sort of problem that you can have, try
compiling this...

/* start of overflow_test.c */
#include <stdio.h>

int main( void )
	{
	unsigned int a;
	char b[1];
	unsigned int c;

	a = 0x00;
	c = 0x00;
	printf("The value of a is 0x%08x\n", a);
	printf("The value of c is 0x%08x\n", c);
	printf("\nEnter a string of 6 characters\n");
	gets( b );
	printf("You entered %s\n", b);
	printf("The value of a is 0x%08x\n", a);
	printf("The value of c is 0x%08x\n", c);
	return 0;
	}

Be aware that if you enter too many characters, you will end up with a
SEGFAULT. However, if you enter 6 or fewer, it will overwrite the
variable c.

Hope this helps :-)
-- 
Andrew Edgecombe <andrew.edgecombe at spheresystems.com.au>




More information about the Courses mailing list