开发者

How do I prevent a char pointer buffer overflow?

i.e. -

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

so if the text in table some how was 500 chars long and txt in the m开发者_JAVA技巧ain was only defined as 100....

thanks.


You need to

  • 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...)


You should be able to use snprintf to limit the amount of the buffer that is used.

function(char* txt, size_t length)
{
   int rv;
   rv = snprintf(txt, length, "select * from %s;", table);
   //How do I set last char in buffer to NULL here?
   if (rv >= length) {
       // error
   }
}


About the only thing you can do is malloc enough memory, format the string into that memory, and return a pointer to it. The calling function would then be responsible for freeing the memory when done with it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜