bad.c

/*
 * program to show problems with gets()
 *
 * NOTE: buffer overflow causes an abort if compiled with gcc
 * to demonstrate what happens, use -fno-stack-protector
 *
 * Matt Bishop, ECS 36A
 * April 4, 2024	from a buffer overflow program
 */
#include <stdio.h>

int main(void)
{
	int i = 4;	/* before the buffer */
	char buf[10];	/* input buffer */
	int j = 5;	/* after the buffer */

	/*
	 * read the input
	 */
	if (gets(buf) == NULL){
		printf("Didn't read anything!\n");
		return(1);
	}

	/*
	 * print out result; on buffer overflow,
	 * i or j may change (or both, depending
	 * on where the compiler puts them)
	 */
	printf("Buffer is %s, i = %d, j = %d\n", buf, i, j);

	/* done! */
	return(0);
}


UC Davis sigil
Matt Bishop
Office: 2209 Watershed Sciences
Phone: +1 (530) 752-8060
Email: mabishop@ucdavis.edu
ECS 36A, Programming & Problem Solving
Version of April 2, 2024 at 12:13PM

You can get the raw source code here.

Valid HTML 4.01 Transitional Built with BBEdit Built on a Macintosh