Code:
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
// asprintf() and vasprintf() exists on glibc, but we can make our own,
// to match ISO 9899 specs.
char *vasprintf_( const char *, va_list );
char *asprintf_( const char *fmt, ... );
// FIXED: This is a C program, so main() should be main(void) or main(int, char *[]).
int main( void )
{
const int x = 2147447412;
char *buffer; // Instead of declaring a fixed sized array, because
// you don't know how many chars will fit the MAXIMUM int,
// let's allocate it dynamically, shall we?
size_t sz;
buffer = asprintf_ ( "%d", x );
if ( ! buffer )
{
fputs( "ERROR allocating memory.\n", stderr );
return EXIT_FAILURE;
}
sz = strlen( buffer );
printf ( "\"%s\" (x=%d)\n"
"Length of buffer is %zu bytes\n",
buffer, x, sz + 1 );
// FIXME: To reverse the string we can do it scanning only to
// the middle...
_Bool palindromic = 1;
for ( size_t i = 0; i < sz / 2; i++ )
if ( buffer[i] != buffer[sz - i -1] )
{
palindromic = 0;
break;
}
printf ( "%d is%s palindromic!\n", x, palindromic ? "" : "n't" );
free( buffer );
return EXIT_SUCCESS;
}
char *vasprintf_( const char *fmt, va_list args )
{
int sz;
char *p;
va_list args_copy;
va_copy( args_copy, args );
sz = vsnprintf( NULL, 0, fmt, args_copy );
va_end( args_copy );
if ( sz < 0 )
return NULL;
p = malloc( sz + 1 );
if ( p )
vsprintf( p, fmt, args );
return p;
}
char *asprintf_( const char *fmt, ... )
{
char *p;
va_list args;
va_start( args, fmt );
p = vasprintf_( fmt, args );
va_end( args );
return p;
}