snprintf truncates the last sign
Consider the following code:
char *myContent = "content";
int size = snprintf(NULL, 0, "INSERT INTO myTable (col1) VALUES('%s')",myContent);
char *query = malloc(size+2);
snprintf(query, size, "INSERT INTO myTable (col1) VALUES('%s')",myContent);
Now I have the problem that the last bracket is truncated:
(gdb) print query
$2 = 0x61608开发者_运维百科0 "INSERT INTO myTable (col1) VALUES('content'"
This is not a valid SQL statement, so have you an idea what the reason could be that the last bracket is missing?
snprintf
returns:
the number of characters printed (not including the trailing '\0' used to end output to strings)
But the size argument is:
and vsnprintf() write at most size bytes (including the trailing null byte ('\0'))
So you should:
char *query = malloc(size+1);
snprintf(query, size+1, "INSERT INTO myTable (col1) VALUES('%s')",myContent);
snprintf returns the size of the resulting string, not including the NULL terminator. I think you need to pass size+1 to the second snprintf.
What the others have said. But as myContent hasn't changed, it's safe to simply say:
sprintf(query, "INSERT INTO myTable (col1) VALUES('%s')",myContent);
精彩评论