Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

va_arg(ap,char*) and strcat

Status
Not open for further replies.

cmancre

Programmer
Jan 30, 2005
35
0
0
PT
code:

// n = 2
void fun(int n, ...){
va_list ap;
int i;
char *arg1 = (char *) malloc(MAX * sizeof(char));
char *arg2 = (char *) malloc(MAX * sizeof(char));
va_start(ap, n);
memset(arg1,0,MAX);
memset(arg2,0,MAX);
arg1 =(char*)va_arg(ap,char*);
arg2 =(char*)va_arg(ap,char*);
fprintf(stdout,"%s",strcat(arg1,arg2);
va_end(ap);
}

problem: strcat dont concatenate the two arguments, help!!

 
You malloc to [tt]arg1[/tt] and [tt]arg2[/tt], then later assign these pointers elsewhere, leaking memory. The pointers are then pointing to the arguments passed to the function. If you can't concatenate them (if the pointers point to non-writeable string literals, for example), it may be because of these arguments.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

void fun(int n, ...)
{
   char *arg1, *arg2, *arg;
   va_list ap;
   va_start(ap, n);
   arg1 = va_arg(ap, char*);
   arg2 = va_arg(ap, char*);
   va_end(ap);
   arg  = malloc(strlen(arg1) + strlen(arg2) + 1);
   if ( arg )
   {
      strcpy(arg, arg1);
      fprintf(stdout,"%s\n", strcat(arg, arg2));
      free(arg);
   }
}

int main()
{
   fun(2, "one", " two");
   return 0;
}

/* my output
one two
*/
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top