Memory allocation probe with some rails and meaningful return value.
- /* Overdone Q&D test of max allocation
- // with some rails and meaningful return value
- // by Joel Matthew Rees, 17 Feb 2017
- //
- // Copyright 2017 Joel Matthew Rees
- //
- // 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.
- //
- // (MIT template license.)
- */
- #include <stdlib.h>
- #include <stdio.h>
- int main( int argc, char *argv[] )
- {
- unsigned long gig_count = 4;
- char * block = NULL;
- unsigned long long address = (unsigned long long) NULL; /* Protect us from libraries that sniff freed pointers. */
- int argx;
- int quiet = 0;
- for ( argx = 1; argx < argc; ++argx )
- { char * marker = argv[ argx ];
- if ( ( marker[ 0 ] == '-' ) && ( marker[ 1 ] == 'q' ) )
- { quiet = 1;
- }
- else
- { unsigned long count = strtoul( argv[ argx ], &marker, 0 );
- if ( marker > argv[ argx ] )
- { gig_count = count;
- }
- else
- { if ( !quiet )
- {
- printf( "usage: %s { size-in-GiB } { -q(uiet) }\n", argv[ 0 ] );
- printf( "\tReturns EXIT_FAILURE if malloc fails,\n\t\totherwise EXIT_SUCCESS.\n" );
- {
- size_t size_t_max = 1;
- size_t next;
- unsigned long gigs = 0;
- while ( ( next = size_t_max << 1 ) > 0 )
- { size_t_max = next ;
- }
- gigs = size_t_max / 0x100000000;
- printf( "\tMax size_t is %lu GiB or so.\n", gigs << 1 );
- }
- }
- return EXIT_FAILURE;
- }
- }
- }
- address = (unsigned long long) ( block = malloc( (size_t) gig_count * 0x100000000LL ) );
- free( block ); /* Just in case we allocated everything available. */
- if ( !quiet )
- { printf( "Attempt to malloc %lu GiB yields block address 0x%08llx: %s\n",
- gig_count, address, ( address == (unsigned long long) NULL ) ? "FAILED" : "SUCCEEDED" );
- }
- return ( address == (unsigned long long) NULL ) ? EXIT_FAILURE : EXIT_SUCCESS;
- }