473,748 Members | 10,649 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with Variable-Length Argument Lists

Greetings everyone,

I wrote a function to learn about variable-length argument lists. I
wonder if there is a better way to detect the end of the argument list
than using a sentinel value like the one I am using (NULL in this
example) or an argument count parameter (ugh).

The following function concatenates a series of C-style strings. I am
aware of the fact that not allocating enough memory for `dst` results
in UB (gave me a segmentation fault).

#include <stdarg.h>

char *
append (
char * dst, // destination string buffer
const char * base, // first string
const char * append, // second string
/* const char * appN */ ... // n strings
/* , NULL */ // sentinel null indicating list end
)
{
va_list ap;
char * eosdst = dst;
const char * cp = NULL;

/* copy base to dst */
while ((*eosdst = *base))
++eosdst, ++base;

/* copy append to dst */
while ((*eosdst = *append))
++eosdst, ++append;

/* copy remaining strings if they exist. NULL -- terminate */
va_start (ap, append);
while (NULL != (cp = va_arg (ap, const char*)))
while ((*eosdst = *cp))
++eosdst, ++cp;
va_end (ap);

return (dst);
}

Sample Usage:
#include <stdio.h>

/* ... */

int
main (int argc, char ** pp_argv)
{
char buf[200];
char * tst = "test";
char * teststring2 = "This is some more text.\nSee if this works
well.";

append (buf, "--d--", teststring2, teststring2, tst, "\n", NULL);
printf (buf);

return (0);
}

Any help will be appreciated. If you have suggestions, please feel free
to comment so I can improve. Thank you.

Regards,
JB

Nov 14 '05 #1
5 1966
Jonathan Burd wrote:
Greetings everyone,

I wrote a function to learn about variable-length argument lists. I
wonder if there is a better way to detect the end of the argument list
than using a sentinel value like the one I am using (NULL in this
example) or an argument count parameter (ugh).
The fundamental requirement is that you need to know
whether a "next argument" exists (and what type it is)
before attempting to retrieve it with va_arg(). You can
use any imaginable computation to come up with this yes/no
result. However, the <stdarg.h> mechanism itself doesn't
provide any information you can use as an input for the
computation; you must compute yes/no from other sources.

Two popular mechanisms are to use a sentinel value or
to use an argument count (which could, of course, actually
count pairs of arguments, or triples, or some other grouping).
A less popular mechanism is to imitate the printf() family,
where one of the "fixed" arguments provides information
about the number and types of the variable arguments. But
these three are by no means an exhaustive catalog; anything
at all will work if it can produce the answer you need. The
trade-offs are usually the mechanism's complexity (simpler
is better, other things being equal) and its vulnerability
to misuse (the compiler can't do a lot of checking on the
"..." arguments).
The following function concatenates a series of C-style strings. I am
aware of the fact that not allocating enough memory for `dst` results
in UB (gave me a segmentation fault).

char *
append (
char * dst, // destination string buffer
const char * base, // first string
const char * append, // second string
/* const char * appN */ ... // n strings
/* , NULL */ // sentinel null indicating list end
)
[...]

Sample Usage:
#include <stdio.h>

/* ... */

append (buf, "--d--", teststring2, teststring2, tst, "\n", NULL);


Here's an example of the "vulnerabil ity to misuse" mentioned
above: write `(char*)NULL' instead of just `NULL'. Question 5.2
in the comp.lang.c Frequently Asked Questions (FAQ) list

http://www.eskimo.com/~scs/C-faq/top.html

explains why.

--
Er*********@sun .com

Nov 14 '05 #2
Jonathan Burd wrote:

I wrote a function to learn about variable-length argument lists.
I wonder if there is a better way to detect the end of the argument
list than using a sentinel value like the one I am using (NULL in
this example) or an argument count parameter (ugh).

The following function concatenates a series of C-style strings. I
am aware of the fact that not allocating enough memory for `dst`
results in UB (gave me a segmentation fault).

#include <stdarg.h>

char *
append (
char * dst, // destination string buffer
const char * base, // first string
const char * append, // second string
/* const char * appN */ ... // n strings
/* , NULL */ // sentinel null indicating list end
)
{
va_list ap;
char * eosdst = dst;
const char * cp = NULL;

/* copy base to dst */
while ((*eosdst = *base))
++eosdst, ++base;

/* copy append to dst */
while ((*eosdst = *append))
++eosdst, ++append;

/* copy remaining strings if they exist. NULL -- terminate */
va_start (ap, append);
while (NULL != (cp = va_arg (ap, const char*)))
while ((*eosdst = *cp))
++eosdst, ++cp;
va_end (ap);

return (dst);
}

Sample Usage:
#include <stdio.h>

/* ... */

int
main (int argc, char ** pp_argv)
{
char buf[200];
char * tst = "test";
char * teststring2 = "This is some more text.\nSee if this works
well.";

append (buf, "--d--", teststring2, teststring2, tst, "\n", NULL);
printf (buf);

return (0);
}

Any help will be appreciated. If you have suggestions, please feel free
to comment so I can improve. Thank you.


You should properly indent your code, using spaces, not tabs. At
any rate variadic functions are invitations to misuse and are error
prone. You should avoid them. Especially in this case, since the
standard sprintf() routine is already available to perform the same
job, is more flexible, uses familiar parameters, and is already
available. With C99 I believe snprintf() is much safer.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #3
Actually, it's Google's posting mechanism. It formatted the code
automatically. I use the 2-space indentation style.

Regards,
JB

Nov 14 '05 #4
In article <41************ ***@yahoo.com>,
CBFalconer <cb********@wor ldnet.att.net> wrote:
Especially in this case, since the
standard sprintf() routine is already available to perform the same
job, is more flexible, uses familiar parameters, and is already
available. With C99 I believe snprintf() is much safer.


I wonder. Is it ever possible in this NG to post something like "I am
trying to solve <newProblemThat HasNeverBeenSol vedBefore>, using technique
<A>, but since newProblemThatH asNeverBeenSolv edBefore is complicated and
possibly proprietary, I'd prefer not to explain
newProblemThatH asNeverBeenSolv edBefore. So, I'm going to discuss the
problems I am having with technique <A>, but I'm going to use this made up
example", and not get a response that says "'made-up-example' has already
been solved; why are you trying to reinvent the wheel?" ?

Nov 14 '05 #5
ga*****@yin.int eraccess.com (Kenny McCormack) writes:
In article <41************ ***@yahoo.com>,
CBFalconer <cb********@wor ldnet.att.net> wrote:
Especially in this case, since the
standard sprintf() routine is already available to perform the same
job, is more flexible, uses familiar parameters, and is already
available. With C99 I believe snprintf() is much safer.


I wonder. Is it ever possible in this NG to post something like "I am
trying to solve <newProblemThat HasNeverBeenSol vedBefore>, using technique
<A>, but since newProblemThatH asNeverBeenSolv edBefore is complicated and
possibly proprietary, I'd prefer not to explain
newProblemThatH asNeverBeenSolv edBefore. So, I'm going to discuss the
problems I am having with technique <A>, but I'm going to use this made up
example", and not get a response that says "'made-up-example' has already
been solved; why are you trying to reinvent the wheel?" ?


Probably, but I see no sign of any
newProblemThatH asNeverBeenSolv edBefore in this thread.

--
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.
Nov 14 '05 #6

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

Similar topics

0
1919
by: Daniel CAUSSE | last post by:
Hello, I'm testing gettext on my website but it doesn't work. phpinfo returns correct informations: configure command => '--with-gettext=/usr' GetText Support => enabled I have no problem to create messages.mo and messages.po files. I've created all directories under a 'locale' root directory
10
2277
by: Jacek Generowicz | last post by:
Where can I find concise, clear documentation describing what one has to do in order to enable Python's internal help to be able to provide descriptions of Python keywords ? I am in a situation where I have to give Python novices the ability to fix this for themselves easily. Failing "concise" and "clear", how about "complete and correct" ?
0
1360
by: Anuj Mathur | last post by:
Hello All We are making an application for translating the literals (HTML text and labels) of an existing ASP website from English to another language, say Swedish. Now, for this we are employing XML document to store the literals and their translations. The literals are passed as string parameters to a translation routine that picks up the translated value from the XML. The XML has a ID-
2
1933
by: Bobby | last post by:
Hello everyone I have a question. The school I am working for is in the beginning process of having a webpage that will direct students to download there homework and be able to view there info like test scores and etc(the homework and info page will reside on our webservers at the school on the local intranet network). Now what I need is a way for the students to go to a login page and when logging in will be automatically directed to...
0
1754
by: Hugo Wetterberg | last post by:
Hi, I've got a problem with RegEx in the 2.0 Beta. I have a regexp expression that works fine in the 1.1 version of the framework but breaks in 2.0. I'm no regexp guru, so I don't really know why version 2.0 returns incorrect results. I have this string: value,Var,],'Text',,pro(a,b,c)
4
1121
by: Jacob.Bruxer | last post by:
Hi, I'm pretty new to Visual Basic and was wondering if anyone could give some general advise on how to conserve memory when running a Visual Basic program that I've created. I keep getting a "Win32 exception was unhandled" error, and I'm pretty sure resource usage is the problem. This might be way too general of a question, so I'll try to explain what it is I'm trying to do as briefly as I can. Basically, my program reads a text file...
1
6096
by: al2004 | last post by:
Write a program that reads information about youth soccer teams from a file, calculates the average score for each team and prints the averages in a neatly formatted table along with the team name. Please follow the specifications for assignment 3 as described below otherwise points will be taken off. Input from a file Please create an input file named input.txt using a text editor like notepad or the Visual C++ editor and put the following...
0
1909
by: magicofureyes | last post by:
Hello Guys im a just a new user and i dnt knw much abt Xml i want to upload a new template in Blogger so got some free coding but when i save this code in Blogger template it say '''' Your template could not be parsed as it is not well-formed. Please make sure all XML elements are closed properly. XML error message: The element type "Variable" must be terminated by the matching end-tag "". so please help me out and check this coding if...
0
8991
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
9541
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
9370
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
9321
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
9247
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...
1
6796
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2782
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
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.