考虑以下代码:
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);
现在我遇到了最后一个括号被截断的问题:
(gdb) print query
$2 = 0x616080 "INSERT INTO myTable (col1) VALUES('content'"
这不是有效的 SQL 语句,所以您知道缺少最后一个括号的原因是什么吗?
最佳答案
snprintf
返回:
the number of characters printed (not including the trailing '\0' used to end output to strings)
但是大小参数是:
and vsnprintf() write at most size bytes (including the trailing null byte ('\0'))
所以你应该:
char *query = malloc(size+1);
snprintf(query, size+1, "INSERT INTO myTable (col1) VALUES('%s')",myContent);
关于mysql - snprintf 截断最后一个符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6322185/