mysql - snprintf 截断最后一个符号

标签 mysql c insert

考虑以下代码:

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/

相关文章:

mysql - 试着数数我的数

php - 如何根据其他列值输出SQL列?

mysql - 从 mysql 表中获取产品摘要

c - union 和通用功能

c - 如何从字符串中提取数字并将它们保存到自己的缓冲区中?

javascript - 如何在对象中显示数据

我可以使用 Microchip 的 MPLAB 在 C 中对 PIC 16f628a 进行编程吗?

php - MySql PHP 插入与连接

php - 插入 MySQL 无法正常工作

PHP插入两个不同的表