开发者

snprintf truncates the last sign

开发者 https://www.devze.com 2023-03-12 13:58 出处:网络
Consider the following code: char *myContent = \"content\"; int size = snprintf(NULL, 0, \"INSERT INTO myTable (col1) VALUES(\'%s\')\",myContent);

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?


snprintfreturns:

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消