Skip to content

Instantly share code, notes, and snippets.

@masterl
Created January 1, 2016 18:05
Show Gist options
  • Save masterl/68f51563173e9271c529 to your computer and use it in GitHub Desktop.
Save masterl/68f51563173e9271c529 to your computer and use it in GitHub Desktop.
Short source demonstrating the effects of using the wrong specifier on scanf
// The MIT License (MIT)
// Copyright (c) 2016 Leonardo de Oliveira Lourenço
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <stdio.h>
void print_short_v( short *v, size_t length );
int main( void )
{
short v[3] = {0x2525, 0x2525, 0x2525};
printf( "Sizeof short: %2lu\n", sizeof( short ) );
printf( " Sizeof int: %2lu\n", sizeof( int ) );
printf( "\nVector before reading:\n" );
print_short_v( v, 3 );
if( sizeof( short ) == sizeof( int ) )
{
printf( "\nThis program is meant to demonstrate failure when reading a short as "
"an int, but their sizes are equal on your environment. Sorry.\n" );
}
else
{
printf( "\nPlease input an integer: " );
scanf( " %d", v + 1 );
printf( "\nVector after reading:\n" );
print_short_v( v, 3 );
}
printf( "\n\nProgram endend.\n" );
return 0;
}
void print_short_v( short *v, size_t length )
{
size_t i;
for( i = 0; i < length; ++i )
{
printf( "%5hd ", v[i] );
}
printf( "\n" );
}
@masterl
Copy link
Author

masterl commented Jan 1, 2016

Example output:
screenshot_2016-01-01_16-14-20

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment