Snprintf man page memory leak example?

The Linux man page for snprintf (3) shows an example:

#include <stdio.h> #include <stdlib.h> #include <stdarg.h> char * make_message(const char *fmt, ...) { int n; int size = 100; /* Guess we need no more than 100 bytes */ char *p, *np; va_list ap; if ((p = malloc(size)) == NULL) return NULL; while (1) { /* Try to print in the allocated space */ va_start(ap, fmt); n = vsnprintf(p, size, fmt, ap); va_end(ap); /* Check error code */ if (n < 0) return NULL; /* If that worked, return the string */ if (n < size) return p; /* Else try again with more space */ size = n + 1; /* Precisely what is needed */ if ((np = realloc (p, size)) == NULL) { free(p); return NULL; } else { p = np; } } } 

After /* check error code */ this should not be:

  if (n < 0) { free(p); return NULL; } 

to avoid memory leak?

I can't post this because the word-to-code relationship is wrong, so I need to add more text at the end. Please ignore this paragraph as the above is complete and accurate. Hope this is enough for the text to be acceptable.

By the way: I like the last line p = np;

+7
c linux printf manpage
source share
2 answers

Yes, this code is leaky.

vsnprintf may return a negative number on error. In VC ++, vsnprintf returns -1 when the target buffer is too small, which breaks the logic in this code ... Look here: MSDN The implementation of VC is not consistent with the C standard ...

Other sources for vsnprintf failure send a NULL format buffer or bad encoding in the format buffer.

+2
source share

I do not know that strlen will ever return a value less than zero from n = vsnprintf(...) , but if it was executed (and size > 0 ), this will certainly lead to a memory leak.

The make_message function performs a simple return NULL; without freeing the memory allocated by it p = malloc(size) . It is missing free(p); just as you stated in your original question.

0
source share

All Articles