Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 main was only defined as 100....

thanks.

like image 487
T.T.T. Avatar asked Dec 10 '22 16:12

T.T.T.


2 Answers

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

like image 69
James McNellis Avatar answered Jan 01 '23 05:01

James McNellis


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
   }
}
like image 44
WhirlWind Avatar answered Jan 01 '23 04:01

WhirlWind