Search code examples
cfunctionargumentsparameter-passingvariadic-functions

Couldn't implement function with variable arguments


I was trying to implement function with variable arguments but was getting garbage values as output.I have referred this article before trying to implement on my own.Could anyone help me out with this code as I am unable to understand what's wrong in this code.

/* va_arg example */
#include <stdio.h>      /* printf */
int FindMax (int n, ...)
{
    int i,val,largest,*p;
    p=&n;
    p+=sizeof(int);
    largest=*p;
    for (i=1;i<n-2;i++)
    {
        p+=sizeof(int);
        val=*p;
        largest=(largest>val)?largest:val;
    }
    return largest;
}
int main ()
{
    int m;
    m= FindMax (7,702,422,631,834,892,104,772);
    printf ("The largest value is: %d\n",m);
    return 0;
}

Solution

  • The problem is that you try to access locations on the stack directly where you assume to find your arguments. Calling conventions are machine- and sometimes compiler-specific and an implementation detail you can never rely on, so probably your arguments are not found on the stack where you assume they are. In terms of C, your code just invokes undefined behavior

    Solution: use stdarg.h for accessing the arguments, that's what it's there for.

    #include <stdio.h>      /* printf */
    #include <stdarg.h>
    
    int FindMax (int n, ...)
    {
        va_list ap;
        int i,val,largest;
    
        va_start(ap, n); // <- ap is the argument pointer, this initializes it
                         //    based on the last non-variadic argument.
    
        largest=0;
        while (n--)
        {
            val = va_arg(ap, int); // <- fetch argument and advance pointer
            largest=(largest>val)?largest:val;
        }
        va_end(ap); // done with argument pointer
    
        return largest;
    }
    int main ()
    {
        int m;
        m= FindMax (7,702,422,631,834,892,104,772);
        printf ("The largest value is: %d\n",m);
        return 0;
    }