vBulletin Search Engine Optimization
| |||||||
| Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| ||||
| On Wed, Apr 13, 2005 at 06:18:52PM -0700, William Ahern wrote: > On Thu, Apr 14, 2005 at 03:00:38AM +0159, Han Boetes wrote: > > OK, scratch that. > > > > Since the manpage is confusinging me I wrote this to get insight > > in what happens: > > > > % cat test.c > > #include <stdio.h> > > #include <string.h> > > > > int > > main(void) > > { > > int ret; > > int max = 6; > > char returnstring1[8] = "yadadad"; > > char returnstring2[6] = "yadad"; > > char returnstring3[4] = "yad"; > > char returnstring4[2] = "y"; > > > > printf("strlen(returnstring1) = %i \n", strlen(returnstring1)); > > printf("strlen(returnstring2) = %i \n", strlen(returnstring2)); > > printf("strlen(returnstring3) = %i \n", strlen(returnstring3)); > > printf("strlen(returnstring4) = %i \n", strlen(returnstring4)); > > > > ret = snprintf(returnstring1, max, "%s%s", "foo", "bar"); > > printf("ret = %i, returnstring1 = %s, lenght = %i\n", ret, returnstring1, strlen(returnstring1)); > > > > ret = snprintf(returnstring2, max, "%s%s", "foo", "bar"); > > printf("ret = %i, returnstring2 = %s, lenght = %i\n", ret, returnstring2, strlen(returnstring2)); > > > > ret = snprintf(returnstring3, max, "%s%s", "foo", "bar"); > > printf("ret = %i, returnstring3 = %s, lenght = %i\n", ret, returnstring3, strlen(returnstring3)); > > You just overflowed returnstring3. > > > > > ret = snprintf(returnstring4, max, "%s%s", "foo", "bar"); > > printf("ret = %i, returnstring4 = %s, lenght = %i\n", ret, returnstring4, strlen(returnstring4)); > > You just overflowed returnstring4; > > > return 0; > > } > > > > So if you are not so sure what the result will be, please write > > down what you think it will be and only then compile and see what > > it does. > > In all cases ret should be 6. > > > If you do know what happens, /me bows for you in awe, and please > > tell me why it does. Because it doesn't make sense to me. I > > expected really something different. > > snprintf(3) doesn't discard any useful information. snprintf(3) returns the > _logical_ length of the string; that is, the length assuming an infinite > buffer. However, it will only write the resulting string up to the > [declared] size of the buffer, minus one (for the NUL). On a successful > return (ret >= 0) snprintf(3) guarantees to NUL terminate the buffer if > sizeof(buffer) > 0. > > If ret >= sizeof(buffer) then your string was truncated. The length of the > string in the buffer is then sizeof(buffer) - 1. > actually, in this example, he is not using sizeof(buffer) as the second agrument to snprintf. so in the example, if ret >= max, then the string was truncated ret - max + 1 characters. if max > sizeof(buffer) && ret >= sizeof(buffer), then buffer was overflowed. -- <jakemsr@jakemsr.com> |