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.
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.
You need to
snprintf()
instead of sprintf()
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.