#include // allows uint16_t, int64_t #include #include #include #include #include char progid[80] = "square_it.c by John Copeland 4/1/2011, 3/31/14" ; void pr_buf( char* p, int m) { int i ; printf("The memory address of buff is %x\n", (uint32_t) p ); for( i=0 ; i< m ; i++ ) { if(( p[i] > 31 ) && ( p[i] < 127 )) // 32 is space, 127 is delete, printf("%c,", p[i] ) ; else printf("%2x,", (unsigned char) p[i] ) ; // print as 2-space hex, -128 to 31, and 127 } printf("\n") ; return ; } int do_square( int x) // "x" here is a local variable, stored in a different { // location (on the stack) from the "x" in main x = x * x ; return( x ) ; } int main(int argc, char * argv[ ]) { int x, y ; // modern: replace "int" with "int32_t" char buf[5] ; printf("\n%s\n", progid ) ; while(1) { printf("\n Type number (q = quit) : ") ; gets( buf ) ; if( buf[0] == 'q' ) break ; x = atoi( buf ) ; printf(" ---- x = %i buf = %s\n", x, buf ) ; pr_buf( buf, 50 ) ; y = do_square( x ) ; printf("--The square of %i is %i\n", x, y ); } return( 0 ) ; } /* ============= EXAMPLE OUTPUT ============== square_it.c by John Copeland 4/1/2011, 3/31/14 Type number (q = quit) : 3 ---- x = 3 buf = 3 The memory address of buff is 5fbff910 3, 0,bf,_,ff,, 0, 0,R,10,c0,_, 3, 0, 0, 0,0,f9,bf,_,ff,, 0, 0,fc, c, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,18,fa, --The square of 3 is 9 Type number (q = quit) : 3 This_is_overflowing_the_buffer. ---- x = 3 buf = 3 This_is_ov 3, ,T,h,i,s,_,i,s,_,o,v, 3, 0, 0, 0,o,w,i,n,g,_,t,h,e,_,b,u,f,f,e,r,., 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0,18,fa, --The square of 3 is 9 Type number (q = quit) : q Segmentation fault // we overwrote the return address of main() ========================== */