views:

188

answers:

3

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.

+12  A: 

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

James McNellis
Thanks, I was not sure if there was any other way.
Tommy
+3  A: 

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
   }
}
WhirlWind
You do need to check the return value of `snprintf()` though - truncation in case is clearly an error that needs to be handled.
caf
@caf thanks; updated.
WhirlWind
A: 

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.

sizzzzlerz
You can do a lot more than that.
WhirlWind