There is a code snippet:

char *dbname = valueOfParam("dbname"); char *dbuser = valueOfParam("dbuser"); char *dbpass = valueOfParam("dbpass"); char *conninfo; // Then I try compile new variable like this: printf("PQconnectdb(\"dbname=%s host=localhost user=%s password=%s\");", dbname, dbuser, dbpass); // But I need create the variable sprintf(conninfo, "PQconnectdb(\"dbname=%s host=localhost user=%s password=%s\");", dbname, dbuser, dbpass); 

How to allocate memory for conninfo ? Indeed, without allocating the required amount of memory, the code is incorrect.

  • strlen ("PQconnectdb (\" dbname = host = localhost user = password = \ ");") + strlen (dbname) + strlen (dbuser) + strlen (dbpass) + 1 - Vladimir Martyanov
  • man asprintf something. And all the participants of this cozy chat. - 0andriy

1 answer 1

I would use the fact that when snprintf to it buffer size 0, it returns the number of characters that it would write (excluding zero).

Those. like that-

 int len = snprintf(NULL,0,......); char * buf = malloc(len+1); 
  • Varint work too: char * conninfo = malloc (sizeof (char) * (strlen ("PQconnectdb (\" dbname = host = localhost user = password = \ ");") + strlen (dbname) + strlen (dbuser) + strlen (dbpass) + 1)); - Irbis
  • @Irbis Option. But - not universal, by contrast. What to do for %d , or something else? Hands to repeat the functionality of sprintf , instead of to use the existing one? - Harry
  • man asprintf something. - 0andriy
  • @ 0andriy As soon as you show the appropriate place in the standard - no questions asked ... - Harry
  • one
    @ 0andriy No, it is necessary to clearly indicate in the question the possibility of using non-standard things. I can equally well refer to my function in my library - and what, this will be the solution? :) Ah, okay, I’ve got used to it, that if they give you a ruled one, you’ll write across the principle :) and if you give a spelling dictionary, well, it’s scary to imagine what will be written ... In general, my discussion is over :) - Harry