gpt4 book ai didi

mysql - snprintf 截断最后一个符号

转载 作者:太空宇宙 更新时间:2023-11-04 07:38:43 26 4
gpt4 key购买 nike

考虑以下代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com