Search code examples
cstringurldynamic-memory-allocation

How to build Url dynamically in C


I need to build an url in with Query Params and different API Endpoints. I don't like to use a char array with a fixed sized because memory is wasted and I rely on hoping that the size will be big enough.

#define BASE_URL  "https//mydomain.com/api/"
#define ID "ID1"

char* do_endpoint_request(const char* param)
{
   char url[500];
   snprintf(url, sizeof(url), BASE_URL "endpoint?id=%s&param1=%s", ID, param);
   // do request with url ...

}

How can I improve this code, that memory is allocated dynamically with exact size of the string and params injected?


Solution

  • You can use the fact that snprintf() may be called with NULL instead of an actual buffer and that it returns the length of the string that would have been created if there was enough space. So:

    #define BASE_URL  "https//mydomain.com/api/"
    #define ID "ID1"
    
    char* do_endpoint_request(const char* param)
    {
       int len;
    
       len = snprintf(NULL, 0, BASE_URL "endpoint?id=%s&param1=%s", ID, param);    
       char url[len+1]; // len excludes NULL; use malloc() if you can't use VLA
       // sprintf() is ok now, url is guaranteed to be large enough
       sprintf(url, BASE_URL "endpoint?id=%s&param1=%s", ID, param);
       // do request with url ...
    
    }