Var args of different type return segmentation fault

Viewed 80

I have code in which I have used in varargs one is of type long and the other is of type char array, and it is passed to a function with variable number of argument (...) and when I try to retrieve the char [] it is throwing a segmentation fault.

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

int varargs(int num,...);

int main()
{
   printf("enter fflush\n");
   long opr=77777;
   long *ptr=&opr;
   char env[10]="QATNLO19\0";
   varargs(2,* ptr,env);
   return 0;
}

int varargs(int num,...)
{
    va_list ap;
    va_start(ap,num);
    printf("getting char arg\n"); 
    fflush (stdout);
    char *ptr=va_arg(ap,char *); // segmentation fault at this line 
    printf("char is %s",ptr);
    return 0;
}

Can you explain why this is a segmentation fault?

1 Answers

The first variadic argument passed to the function is *ptr which has type long. You're attempting to read it as if it were a char *. That triggers undefined behavior.

You need to read the long argument first before you can read the char *. You also need to call va_end when you're finished reading the arguments.

long l = va_arg(ap,long);
char *ptr = va_arg(ap,char *);
va_end(ap);
Related