ho provato il codice di @Valentin Milea ma ho errori di violazione di accesso. L'unica cosa che ha funzionato per me è stata l'implementazione di Insane Coding: http://asprintf.insanecoding.org/
In particolare, stavo lavorando con il codice legacy VC++ 2008. Dall'implementazione di Insane Coding (scaricabile dal link sopra), ho utilizzato tre file: asprintf.c
, asprintf.h
e vasprintf-msvc.c
. Altri file erano per altre versioni di MSVC.
[EDIT] Per completezza, il loro contenuto è il seguente:
asprintf.h:
#ifndef INSANE_ASPRINTF_H
#define INSANE_ASPRINTF_H
#ifndef __cplusplus
#include <stdarg.h>
#else
#include <cstdarg>
extern "C"
{
#endif
#define insane_free(ptr) { free(ptr); ptr = 0; }
int vasprintf(char **strp, const char *fmt, va_list ap);
int asprintf(char **strp, const char *fmt, ...);
#ifdef __cplusplus
}
#endif
#endif
asprintf.c:
#include "asprintf.h"
int asprintf(char **strp, const char *fmt, ...)
{
int r;
va_list ap;
va_start(ap, fmt);
r = vasprintf(strp, fmt, ap);
va_end(ap);
return(r);
}
vasprintf-msvc.c:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include "asprintf.h"
int vasprintf(char **strp, const char *fmt, va_list ap)
{
int r = -1, size = _vscprintf(fmt, ap);
if ((size >= 0) && (size < INT_MAX))
{
*strp = (char *)malloc(size+1); //+1 for null
if (*strp)
{
r = vsnprintf(*strp, size+1, fmt, ap); //+1 for null
if ((r < 0) || (r > size))
{
insane_free(*strp);
r = -1;
}
}
}
else { *strp = 0; }
return(r);
}
Utilizzo (parte o f test.c
fornita dalle Coding Insane):
#include <stdio.h>
#include <stdlib.h>
#include "asprintf.h"
int main()
{
char *s;
if (asprintf(&s, "Hello, %d in hex padded to 8 digits is: %08x\n", 15, 15) != -1)
{
puts(s);
insane_free(s);
}
}
... oppure si può semplicemente fare "#define snprintf _snprintf" –
... si potrebbe, ma purtroppo _snprintf() non è la stessa di snprintf() come non garantisce la risoluzione nulla. –
Ok quindi dovrai memsetare a zero prima di usare _snprintf(). Inoltre sono d'accordo con te. Lo sviluppo sotto MSVC è terribile. Anche gli errori sono confusi. – Owl