Slightly different approach:
void zap(char **stmt, char *argument, size_t *stmtBufLen)
{
char *fmt="INSERT INTO test(nazwa, liczba) VALUES ('nowy wpis', '%s')";
/**
* Is our current buffer size (stmtBufLen) big enough to hold the result string?
*/
size_t newStmtLen = strlen(fmt) + strlen(argument) - 2;
if (*stmtBufLen < newStmtLen)
{
/**
* No. Extend the buffer to accomodate the new statement length.
*/
char *tmp = realloc(*stmt, newStmtLen + 1);
if (tmp)
{
*stmt = tmp;
*stmtLen = newStmtLen+1;
}
else
{
/**
* For now, just write an error message to stderr; the statement
* buffer and statement length are left unchanged.
*/
fprintf(stderr, "realloc failed; stmt was not modified\n");
return;
}
}
/**
* Write statement with argument to buffer.
*/
sprintf(*stmt, fmt, argument);
}
int main(void)
{
char *stmtBuffer = NULL;
size_t stmtBufferLen = 0;
...
zap(&stmtBuffer, "foo", &stmtBufferLen);
...
zap(&stmtBuffer, "blurga", &stmtBufferLen);
...
zap(&stmtBuffer, "AReallyLongArgumentName", &stmtBufferLen);
...
zap(&stmtBuffer, "AnEvenLongerRidiculouslyLongArgumentName", &stmtBufferLen);
...
free(stmtBuffer);
return 0;
}
This version uses dynamic memory allocation to resize the buffer as needed, starting with a NULL buffer pointer (realloc(NULL, size) == malloc(size)). This way you don't have to worry about starting out with a buffer that's "big enough". The only drawback is you need to remember to deallocate the buffer when you're done with it (I don't normally like splitting memory management duties between caller and callee like this; if I thought about it for more than 10 minutes, I'd come up with something better).