我如何prevent一个字符指针缓冲区溢出? [英] How do I prevent a char pointer buffer overflow?

查看:126
本文介绍了我如何prevent一个字符指针缓冲区溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即。 -

int function(char* txt)
{
   sprintf(txt, "select * from %s;", table);
   //How do I set last char in buffer to NULL here?
}

因此​​,如果表中的文本一些如何在500个字符长,TXT主才被定义为100 ....

so if the text in table some how was 500 chars long and txt in the main was only defined as 100....

感谢。

推荐答案

您需要


  • 添加的参数,使该缓冲
  • 的大小功能
  • 使用的snprintf()而不是的sprintf()

  • 检查返回值的snprintf()来看看缓冲区需要多大的空间来容纳所有格式的数据;如果这是大于或等于缓冲区的大小,你应该处理您认为合适(缓冲区将仍然是空终止,但将被截断的内容,以适应;这是否是正确的,或者错误完全取决于您的使用情况)

  • add a parameter to the function that gives the size of the buffer
  • use snprintf() instead of sprintf()
  • check the return value of snprintf() to see how large the buffer needed to be to hold all the formatted data; if this is larger than or equal to the size of the buffer, you should handle that as you see fit (the buffer will still be null-terminated, but the contents will be truncated to fit; whether this is okay or an error depends entirely on your use case)

(和你的函数需要返回类型...)

(and your function needs a return type...)

这篇关于我如何prevent一个字符指针缓冲区溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆