How to prevent 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 the table is some kind, like a length of 500 characters, and txt is basically determined only by 100.

thanks.

+4
source share
3 answers

You need

  • add parameter to function that gives buffer size
  • use snprintf() instead of sprintf()
  • check the return value of snprintf() to see how large the buffer should be to store all formatted data; if it is greater than or equal to the size of the buffer, you should handle it as you see fit (the buffer will still be completed with a zero mark, but the contents will be truncated to match whether this is normal or the error depends entirely on your use case)

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

+11
source

You can use snprintf to limit the amount of buffer 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 } } 
+3
source

The only thing you can do is malloc enough memory, format the string in that memory and return a pointer to it. Then the calling function will be responsible for freeing memory when it is executed.

0
source

Source: https://habr.com/ru/post/1309376/


All Articles