0

I'm making a printlnf function, that like printf prints formatted text, but with an added newline at the end, problem is that the number I pass in, comes out as garbage.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

void printlnf(const char* input_string, ...) {
  /* allocate with room for the newline */
  char* fmt_str = malloc(strlen(input_string) + 2);
  strcpy(fmt_str, input_string);
  strcat(fmt_str, "\n");

  /* print the string with the variable arguments */
  va_list argptr;
  va_start(argptr, input_string);
  printf(fmt_str, argptr);

  /* free everything */
  va_end(argptr);
  free(fmt_str);
}

int main(void) {
  printlnf("This is a test of the printlnf");
  printlnf("This is the %dnd line of the print", 2);
  return 0;
}

The output is usually something along the lines of this:

This is a test of the printlnf
This is the 1415441184nd line of the print

How do I fix this?

Electric Coffee
  • 11,733
  • 9
  • 70
  • 131
  • First off, you're not allocating enough space for concatenating the "\n". Don't forget about the terminating null that every C string needs but isn't included in the `strlen()` result. – Michael Burr Oct 16 '14 at 17:25
  • @MichaelBurr but it's a single character, why is that not enough? And what do I write instead to make it enough? – Electric Coffee Oct 16 '14 at 17:26
  • @ElectricCoffee Because there's also `'\0'` character, so you need a `strlen+2`, not `strlen+1`. – Sergey Kalinichenko Oct 16 '14 at 17:27
  • strlen(input_string) + 1('\n') + 1('\0'). – BLUEPIXY Oct 16 '14 at 17:28
  • 1
    The call `printf(fmt_str, argptr);` needs to be a call to `vfprintf()`. It would be simpler to just invoke `vfprintf(input_string, argptr); putchar('\n');` than to allocate, copy, amend, use, destroy the extra format string. – Jonathan Leffler Oct 16 '14 at 17:49

0 Answers0