Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Well, that should be `snprintf()` to start with, but even with that, there are issues. The return type of `snprintf()` is `int`, so it can return a negative value if there was some error, so you have to check for that case. That out of the way, a positive return value is (and I'm quoting from the man page on my system) "[i]f the output was truncated due to this limit then the return value is the number of characters which would have been written to the final string if enough space had been available." So to safely use `snprintf()` the code would look something like:

    int size = snprintf(NULL,0,"some format string blah blah ...");
    if (size < 0) error();
    if (size == INT_MAX)
      error(); // because we need one more byte to store the NUL byte
    size++;
    char *p = malloc(size);
    if (p == NULL)
      error();
    int newsize = snprintf(p,size,"some format string blah blabh ... ");
    if (newsize < 0) error();
    if (newsize > size)
    {
      // ... um ... we still got truncated?
    }
Yes, using NULL with `snprintf()` if the size is 0 is allowed by C99 (I just checked the spec).

One thing I've noticed about the C standard library is that is seems adverse to functions allocating memory (outside of `malloc()`, `calloc()` and `realloc()`). I wonder if this has something to do with embedded systems?



Not just embedded systems, also OSes. C's standard library should generally work without the existence of a heap. After all, you have to create the heap using C before you can allocate from it.


malloc is a required part of ISO C, though.


Functions like malloc are only required for hosted implementations. Many operating systems are built using freestanding implementations.

Further, on many platforms, one should avoid using malloc() unless portability is more important than performance or safety. Some operating systems support useful features like the ability to allocate objects with different expected lifetimes in different heaps, so as to help avoid fragmentation, or arrange to have allocations a program can survive without fail while there is still enough memory to handle critical allocations. Any library that insists upon using "malloc()" will be less than ideal for use with any such operating system.


Also, the return type being int means that there's a limit to the length of your string…




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: