Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1077657
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T21:36:27+00:00 2026-05-16T21:36:27+00:00

How would I only allocate as much memory as really needed without knowing how

  • 0

How would I only allocate as much memory as really needed without knowing how big the arguments to the function are?

Usually, I would use a fixed size, and calculate the rest with sizeof (note: the code isn’t supposed to make sense, but to show the problem):

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

int test(const char* format, ...)
{
    char* buffer;
    int bufsize;
    int status;
    va_list arguments;
    va_start(arguments, format);
    bufsize = 1024; /* fixed size */
    bufsize = sizeof(arguments) + sizeof(format) + 1024;
    buffer = (char*)malloc(bufsize);
    status = vsprintf(buffer, format, arguments);
    fputs(buffer, stdout);
    va_end(arguments);
    return status;
}

int main()
{
    const char* name = "World";
    test("Hello, %s\n", name);
    return 0;
}

However, I don’t think this is the way to go… so, how would I calculate the required buffersize properly here?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T21:36:27+00:00Added an answer on May 16, 2026 at 9:36 pm

    If you have vsnprintf available to you, I would make use of that. It prevents buffer overflow since you provide the buffer size, and it returns the actual size needed.

    So allocate your 1K buffer then attempt to use vsnprintf to write into that buffer, limiting the size. If the size returned was less than or equal to your buffer size, then it’s worked and you can just use the buffer.

    If the size returned was greater than the buffer size, then call realloc to get a bigger buffer and try it again. Provided the data hasn’t changed (e.g., threading issues), the second one will work fine since you already know how big it will be.

    This is relatively efficient provided you choose your default buffer size carefully. If the vast majority of your outputs are within that limit, very few reallocations has to take place (see below for a possible optimisation).

    If you don’t have an vsnprintf-type function, a trick we’ve used before is to open a file handle to /dev/null and use that for the same purpose (checking the size before outputting to a buffer). Use vfprintf to that file handle to get the size (the output goes to the bit bucket), then allocate enough space based on the return value, and vsprintf to that buffer. Again, it should be large enough since you’ve figured out the needed size.


    An optimisation to the methods above would be to use a local buffer, rather than an allocated buffer, for the 1K chunk. This avoids having to use malloc in those situations where it’s unnecessary, assuming your stack can handle it.

    In other words, use something like:

    int test(const char* format, ...)
    {
        char buff1k[1024];
        char *buffer = buff1k; // default to local buffer, no malloc.
        :
        int need = 1 + vsnprintf (buffer, sizeof (buff1k), format, arguments);
        if (need > sizeof (buff1k)) {
            buffer = malloc (need);
            // Now you have a big-enough buffer, vsprintf into there.
        }
    
        // Use string at buffer for whatever you want.
        ...
    
        // Only free buffer if it was allocated.
        if (buffer != buff1k)
            free (buffer);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Supposed that for some reason you are only allowed to use static memory in
How would I create a DecimalFormat that would only have seven digits total and
The Product Tags tab would only appear after a product has been created. Even
I would like to be able to spawn a linux process that would only
Anyone have any idea why shuffle() would only return 1 item? when using: $array2
I made simple email in wordpress but it would only send email to the
I know normally that assigning a name attribute to the radio inputs would only
I'd like to add a keyword to my language. This keyword would only have
I have trouble where, for some reason, SVN would only merge the newly generated
I want to make a registration page for clients, that would only contain a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.