Memory Management
* myprintf.c: Dynamic Memory allocation added
* prog_limit: fixed a segfault
committer: Markus Bröker <mbroeker@largo.homelinux.org>
/**
* test/demos/myprintf.c
* Copyright (C) 2008 Markus Broeker
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#define BUF_SIZE 1024
int myprintf (char *fmt, ...)
{
int i, value, pos = 0, size = 1;
char c;
char *ptr;
char *s;
char *s_str;
char v_str[28];
va_list list;
if ((s_str = malloc (BUF_SIZE)) == NULL) {
return EOF;
}
va_start (list, fmt);
while (*fmt) {
switch (*fmt) {
case '%':
switch (*++fmt) {
case 'c':
c = va_arg (list, int);
s_str[pos++] = c;
break;
case 's':
s = va_arg (list, char *);
while ((pos + strlen (s)) > (size * BUF_SIZE)) {
if ((ptr = realloc (s_str, ++size * BUF_SIZE)) == NULL) {
s_str[pos] = '\0';
fputs (s_str, stdout); /* print it anyway... */
return EOF;
}
s_str = ptr;
}
for (i = 0; i < strlen (s); i++) {
s_str[pos++] = s[i];
}
break;
case 'd':
value = va_arg (list, int);
sprintf (v_str, "%d", value);
for (i = 0; i < strlen (v_str); i++) {
s_str[pos++] = v_str[i];
}
break;
default:
s_str[pos++] = *fmt;
}
c = *fmt++;
default:
s_str[pos++] = *fmt++;
}
if (pos > (size * BUF_SIZE / 2)) {
if ((ptr = realloc (s_str, ++size * BUF_SIZE)) == NULL) {
return EOF;
}
s_str = ptr;
}
va_end (list);
}
s_str[pos] = '\0';
fputs (s_str, stdout);
free (s_str);
return pos;
}
int main (int argc, char **argv)
{
int len;
len = myprintf ("Printf replacement %% [Version %d - %s]...\n", 5, "LSF Rostock");
return EXIT_SUCCESS;
}