unnugi unnugi - 1 year ago 94
C Question

How to decide the snprintf dest buffer size

Since sprintf will cause some buffer overflow, I need to change all sprintf to snprintf in project. But I got some trouble as following:

void foo( char *a, uchar *string)
sprintf(string, 'format', src_str);

The question is when the destination string is a parameter of the function, how to decide the buffer size or the maximum length of string after we change to snprintf..

Answer Source

If you have the option to allocate the destination-buffer yourself, you can check the length of the source string with strlen() in case it is null-terminatd and allocate a sufficiently large buffer for it and the terminating null-character. You could also use asprintf directly, if it is available. If you do not have that option you will have to pass the size of the destination buffer as argument, because you cannot reliably determine its size from inside the function if you only have the pointer to it (unless the destination buffer is always delimited in a uniquely identifiable way).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download