Wednesday, August 31, 2011

Some more C musings

Still working on getting my C mojo back both for school and for a application project. Here is an example of some (attempting to be overrun safe) dynamic memory alocation:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>


char *speak ( char *bs, unsigned int counter ) {
	char *str    = "Hello %d: %s";

	size_t bs_l  = strlen( bs );
	size_t str_l = strlen( str ) - 2;
	size_t c_l   = counter == 0? 1 : log(counter) / log(10) + 1;
	size_t alloc = str_l + c_l + bs_l;

	char *ptr    = malloc( alloc );
	int written  = snprintf( ptr, alloc, str, counter, bs );

	printf( "(%zd + %zd + %zd) = %zd <> %i: ", str_l, c_l, bs_l, alloc, written );

	return ptr;
}

int main ( void ) {

	unsigned int c;

	for( c = 0; c == c; c = c + 5 ) {
		char *foo = speak("Have a nice day!", c);
		printf("%s\r", foo);
		free( foo );
	} 

	exit(0);
}

No comments:

Post a Comment