Search code examples
cpointersdbus

Get string from variable argument function


I am trying to pass a double pointer to a variable argument function so that I can store a string in it ("hello world" in my example) and then print it from my main function but its not working.

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

void get_value(const char *str,...) {

   va_list valist;

   /* initialize valist for num number of arguments */
   va_start(valist, str);

   /* access all the arguments assigned to valist */
    void *p;
    p = va_arg(valist, void*);

    char *tmp = strdup("hello world");
    *(const char**)p = tmp;

   /* clean memory reserved for valist */
   va_end(valist);

}

int main() {
    const char *t;
    get_value("first", &t);
    printf("%s\n", t);
}

I have tried to follow lib sd-bus implementation because it is used a lot in there but so far I havent been able to fix this issue.

My aim is to use this for mocking of an sd bus method for my unittests.


Solution

  • You're missing an #include.

    None of the includes you have includes a declaration for strdup. Because of this, the compiler uses the implicit function declaration of a function returning an int. A pointer and an int are most likely different sizes on your system. The mismatch between the implicit declaration and the real declaration result in undefined behavior.

    The strdup function requires that you #include <string.h> for the proper declaration.

    Also, because you know that the argument to get_value is of type const char **, you should pass that to va_arg instead of void * and change the type of p to match.