473,595 Members | 2,576 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trouble with va_list processing

Hi,

I have written a very simple program using variable arguments calls and
I
get strange things that I cannot explain.

I have one function (add) that displays two parameters. It works well
when I call it directly.
Now I have a second function (set) that also calls add. But this
doesn't
work.

Here is the output generated by my program. I don't understand why I
get different result (I tried on both Borland C++ Builder and in Visual
C++, and
I got similar results).

Any help would be greatly appreciated.
Thanks
Best Regards
Thierry

ADD format = H%dW%d
arg[] = 1234
arg[] = 5678
SET

format = H%dW%d
arg[] = 1245060
arg[] = 1245060


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

//---------------------------------------------------------------------------
void add (char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format);

printf("format = %s\n",format);
printf("arg[] = %d\n", va_arg (arg_ptr, unsigned long));
printf("arg[] = %d\n", va_arg (arg_ptr, unsigned long));
}
//---------------------------------------------------------------------------
void set (char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format);
add(format, arg_ptr);
}
//---------------------------------------------------------------------------
int main()
{
printf("\n>>>AD D \n");
add("H%dW%d",12 34,5678);

printf("\n>>>SE T \n");
set("H%dW%d",12 34,5678);

return 0;
}

Feb 1 '06 #1
11 3056
"thierrydol lar" <th*****@tetrae dre.com> writes:
I have written a very simple program using variable arguments calls
and I get strange things that I cannot explain.

I have one function (add) that displays two parameters. It works
well when I call it directly. Now I have a second function (set)
that also calls add. But this doesn't work.

Here is the output generated by my program. I don't understand why I
get different result (I tried on both Borland C++ Builder and in
Visual C++, and I got similar results).


I assume you were using both as C compilers; if you're using them as
C++ compilers, you're in the wrong newsgroup. Your program appears to
be within the common subset of C and C++, but there are subtle
differences.

[snip]
ADD format = H%dW%d
arg[] = 1234
arg[] = 5678
SET

format = H%dW%d
arg[] = 1245060
arg[] = 1245060


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

//---------------------------------------------------------------------------
void add (char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format);

printf("format = %s\n",format);
printf("arg[] = %d\n", va_arg (arg_ptr, unsigned long));
printf("arg[] = %d\n", va_arg (arg_ptr, unsigned long));
}
//---------------------------------------------------------------------------
void set (char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format);
add(format, arg_ptr);
}
//---------------------------------------------------------------------------
int main()
{
printf("\n>>>AD D \n");
add("H%dW%d",12 34,5678);

printf("\n>>>SE T \n");
set("H%dW%d",12 34,5678);

return 0;
}


Your call to add() is incorrect, but is likely to work anyway.
When it processes the call
add("H%dW%d",12 34,5678);
the compiler doesn't know that add() is expecting unsigned long
arguments. The constants 1234 and 5678 are of type int. Try either
add("%dW%d", 1234UL, 5678UL);
or
add("%dW%d", (unsigned long1234, (unsigned long)5678);
or change the va_arg() invocations to use int.

This is likely to "work" if int and long are the same size, or if
they're passed with compatible calling conventions and the byte
ordering is just right.

(Also, since the standard *printf() functions use "%d" for type int,
it seems misleading for add() to use it for unsigned long. Presumably
the full version of add() pays attention to the format string -- but
thank you for stripping out that part of the code.)

You forgot to call va_end() in add().

The add() function requires a char* argument followed by zero or more
arguments of unknown types; since it invokes va_arg() with a type of
unsigned long, it will invoke undefined behavior unless you call it
with a char* and two unsigned longs. In set(), you call add() with a
char* and a va_list. The add() function probably tries to interpret
the va_list value as if it were an unsigned long, and then tries to
interpret whatever garbage happens to be where the third argument
*would* have been stored as if it were an unsigned long -- and that's
only with some optimistic assumptions. It's undefined behavior.

By analogy with the standard's printf() vs. vprintf(), you can create
a second function, say vadd(), that takes a format string and a
va_list. Your add() function could then be implemented as:

void add(char *format, ...)
{
va_list arg_ptr;
va_start(arg_pt r, format);
vadd(format, arg_ptr);
va_end(arg_ptr) ;
}

(I've only minimally tested a variant of this code; use with caution.)

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 1 '06 #2
thierrydollar wrote:
I have written a very simple program using variable arguments calls and
I get strange things that I cannot explain. #include <stdio.h>
#include <stdarg.h>

//---------------------------------------------------------------------------
void add (char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format);

printf("format = %s\n",format);
printf("arg[] = %d\n", va_arg (arg_ptr, unsigned long));
printf("arg[] = %d\n", va_arg (arg_ptr, unsigned long));
}
//---------------------------------------------------------------------------
void set (char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format);
add(format, arg_ptr);
The function add expects the second and third argument to be of type
unsigned long, but you pass it a type arg_ptr for the first and nothing
for the second. The result is undefined behavior.
}
//---------------------------------------------------------------------------
int main()
{
printf("\n>>>AD D \n");
add("H%dW%d",12 34,5678);
Add expects two arguments of type unsigned long. You are providing two
arguments of type int. It may work on your system if int and long are
the same size, but is poor practice and not portable.
printf("\n>>>SE T \n");
set("H%dW%d",12 34,5678);

return 0;
}

--
Thad
Feb 1 '06 #3
The problem I described is not related to the type of arguments. I had
also problems when passing strings.

Feb 1 '06 #4
thierrydollar wrote:
The problem I described is not related to the type of arguments. I had
also problems when passing strings.


We (usually) can't debug code we can't see.

--
Chris "understand ing is a three-edged sword" Dollin
Feb 1 '06 #5

I have written another example of the problem with va_list

And here is the result

format = %s
arg[] = hello
format = %s
arg[] = äÂ*↕
Here is the source code

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

//---------------------------------------------------------------------------
void add (char *format, ...)
{
va_list args;
va_start (args, format);

printf("format = %s\n",format);
printf("arg[] = %s\n", va_arg (args, char *));
}
//---------------------------------------------------------------------------
void set (char *format, ...)
{
va_list args;
va_start (args, format);
add(format, args);
}
//---------------------------------------------------------------------------
int main()
{
char txt[] = "hello";
add ("%s",txt);
set ("%s",txt);

return 0;
}
//---------------------------------------------------------------------------

Feb 1 '06 #6
"thierrydol lar" <th*****@tetrae dre.com> writes:
#include <stdio.h>
#include <stdarg.h>

//---------------------------------------------------------------------------
void add (char *format, ...)
{
va_list args;
va_start (args, format);

printf("format = %s\n",format);
printf("arg[] = %s\n", va_arg (args, char *));
}
you don't call va_end().
//---------------------------------------------------------------------------
void set (char *format, ...)
{
va_list args;
va_start (args, format);
add(format, args);
}


you don't call va_end().

add() expects a char *, not a va_list.

DES
--
Dag-Erling Smørgrav - de*@des.no
Feb 1 '06 #7
On 2006-02-01, thierrydollar <th*****@tetrae dre.com> wrote:
The problem I described is not related to the type of arguments. I had
also problems when passing strings.


Probably because you're also doing it wrong when you try to pass
strings.
Feb 1 '06 #8
"thierrydol lar" <th*****@tetrae dre.com> writes:
The problem I described is not related to the type of arguments. I had
also problems when passing strings.


What???

Please read <http://cfaj.freeshell. org/google/> *before* you post
another followup.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 1 '06 #9
Groovy hepcat thierrydollar was jivin' on 31 Jan 2006 15:30:14 -0800
in comp.lang.c.
Trouble with va_list processing's a cool scene! Dig it!
#include <stdio.h>
#include <stdarg.h>

//---------------------------------------------------------------------------
void add (char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format);

printf("format = %s\n",format);
printf("arg[] = %d\n", va_arg (arg_ptr, unsigned long));
%d format specifier with unsigned long argument.
printf("arg[] = %d\n", va_arg (arg_ptr, unsigned long));
%d format specifier with unsigned long argument.
No invokation of the va_end macro.
Assumes 2 unsigned long arguments will always be passed after
format. (Makes a varargs function unnecessary and undesirable.)
Not adding anything. (Makes the function name confusing.)
}
//---------------------------------------------------------------------------
void set (char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format);
add(format, arg_ptr);
Passing a va_list to a function that is expecting two unsigned long
arguments.
No invokation of the va_end macro.
Not setting anything. (Makes the function name confusing.)
}
//---------------------------------------------------------------------------
int main()
{
printf("\n>>>AD D \n");
add("H%dW%d",12 34,5678);
Passing two ints to function expecting two unsigned longs.
printf("\n>>>SE T \n");
set("H%dW%d",12 34,5678);

return 0;
}


If you want to pass a va_list to some function, you must have a
version of the function that takes a va_list. For example:

void vadd(const char *fmt, va_list ap)
{
/* Your code using va_arg(ap, some_type) goes here. */
}

Then your add() function becomes a wrapper around this, like so:

void add(const char *fmt, ...)
{
va_list ap;

va_start(ap, fmt);
vadd(fmt, ap);
va_end(ap);
}

And your set() function is done similarly.
But you must make sure that a) you actually need varargs functions,
b) you don't make assumptions about the number and types of arguments
of varargs functions, c) when processing those arguments, you use them
correctly (eg., don't pass an unsigned long to printf() with a %d
conversion specifier - that's for signed int) and d) you don't pass
variadic arguments of the wrong type (eg., when the function expects
an unsigned long, and you want to pass 1234 to it, cast it to unsigned
long).

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technicall y correct" English; but since when was rock & roll "technicall y correct"?
Feb 3 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
3683
by: Peter | last post by:
-------------------------------------------------------------------------------- Hi, I was wondering if we can create a va_list by adding objects in the va_list instead of passing in the parameter preceding first optional argument? In another words, I want to create a va_list in a similar manner as creating an array. The reason is I want to use FormatMessage() in my program where it
3
16762
by: Douwe | last post by:
I try to build my own version of printf which just passes all arguments to the original printf. As long as I keep it with the single argument version everything is fine. But their is also a version which uses the "..." as the last parameter how can I pass them to the orignal printf ? void myprintf(char *txt, ...) printf(txt, ???????); }
2
3333
by: Joerg Schoen | last post by:
Hi folks! I have a function that gets a 'va_list'. I am passing the 'va_list' two times to a function like 'vprintf' to print it out. I thought that this was portable until I came across a platform (AS/400) where it fails: The 'va_list' is actually defined as some some kind of an array, so passing it happens by *reference*: The first user will destroy it and the second
7
2301
by: Alex | last post by:
Can anyone point me to any good online references about the va_arg() va_list() functions/macros I googled and found a couple of things, but what I found, failed to explain how it really works and give a easy to follow example program Any pointers appreciated.
7
2854
by: Flash Gordon | last post by:
Reading the standard, va_list is an object type (, so I believe the following should be possible: #include <stdarg.h> void foo(va_list *arg) { /* do some stuff which conditionally might read parameters off arg */ }
4
3750
by: goldfita | last post by:
My last post - http://groups.google.com/group/comp.lang.c/browse_thread/thread/eacc2938b4c8ee66/0bdf6ab20a6007d0 I have a little bit more challenging question this time. Suppose I have write_cmd(struct ast_connection *conn, char *msg, ...); I want to call it like (forgive the syntax)
1
9452
by: skillzero | last post by:
Is there a portable way to pass a va_list as a parameter to another function taking a variable argument list? I have a function that takes a printf-like format string and I'd like to use something like %V to pass in another format string and a va_list to allow nesting. It happens to work on my compiler, but I wasn't sure if it's portable to use va_list's as parameters to a variable argument function because va_list isn't always just a...
5
4642
by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
On Jun 3, 3:23 am, Jesse Ziser <d...@spam.diewrote: The relevant paragraph from the Standard is: ---- Begin Quote ---- The type declared is va_list which is an object type suitable for holding information needed by the macros
1
5517
by: Chuck Chopp | last post by:
I have some code that is being built on the following: Windows Server 2003, both 32-bit & 64-bit editions Windows Vista, both 32-bit & 64-bit editions Windows Server 2008, both 32-bit & 64-bit editions Build tools: Visual Studio 2008. SLES 10 SP1, both 32-bit & 64 bit editions
0
7955
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7883
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8261
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8019
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8251
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6674
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
3873
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
1223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.