473,796 Members | 2,480 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

No format string passed to variable argument list function

Hi,

I have a simple printf-like function:

int print(const char *format, ...)
{
char buffer[1024];
va_list argptr;
int i;

va_start(argptr , format);
i = vsnprintf(buffe r, sizeof(buffer), format, argptr);
va_end(argptr);

buffer[sizeof(buffer)-1] = '\0';

printf("%s\n",b uffer); /* this bit just for the sake of testing */

return i;
}

If I call the function using something like:
char message[50];
strcpy(message, "hi there");
print("%s",mess age);

everything works, but if I do:
print(message);

it doesn't (program crashes with an abort).

Is there something wrong with what I'm doing, or should I be looking
elsewhere to work out the cause of my crash?

Thanks a lot,
Adam
Oct 15 '08
30 2759
Peter Nilsson wrote:
Ian Collins <ian-n...@hotmail.co mwrote:
>Keith Thompson wrote:
>>Ian Collins <ian-n...@hotmail.co mwrites:
Adam wrote:
I have a simple printf-like function:
Did you include <stdarg.h>?
He must have; otherwise the identifier "va_arg"
wouldn't be visible.
Or va_list. Yes it was a silly question!

Not necessarily. How do you know Adam isn't using
<varargs.h>?
He would have seen a warning for the va_start with 2 parameters.

--
Ian Collins
Oct 16 '08 #11
Ben Bacarisse <ben.use...@bsb .me.ukwrote:
Peter Nilsson <ai...@acay.com .auwrites:
Adam <n...@snowstone .org.ukwrote:
* printf("%s\n",b uffer);
puts(buffer) is better since the result string
could have % characters...

Did you misread the printf?
Yes, I did.
>*It looks fine to me
It is. I think I was thinking out aloud about the
later...

print(message);

Thanks for pointing it out.

--
Peter
Oct 16 '08 #12
In article <51************ *************** *******@l33g200 0pri.googlegrou ps.com>,
Peter Nilsson <ai***@acay.com .auwrote:
>Adam <n...@snowstone .org.ukwrote:
>I have a simple printf-like function:

int print(const char *format, ...)
{
* char buffer[1024];

Maybe make this static. There's no upper or lower limit
on automatic storage, but I prefer not to allocate more
than 256 bytes in a single function.
(CLC pedant mode)

I would imagine that the lower limit is 0 in most cases.

Are you aware of any implementations that require at least one
automatic object?

Oct 16 '08 #13
On Thu, 16 Oct 2008 08:18:38 +0000, Kenny McCormack wrote:
In article
<51************ *************** *******@l33g200 0pri.googlegrou ps.com>,
Peter Nilsson <ai***@acay.com .auwrote:
>>There's no upper or lower limit on automatic
storage, but I prefer not to allocate more than 256 bytes in a single
function.

(CLC pedant mode)

I would imagine that the lower limit is 0 in most cases.

Are you aware of any implementations that require at least one automatic
object?
(Continued pedant mode)

I think whatever location is used to store the return address qualifies as
an object, and while some may have that location fixed (making it a non-
automatic object), plenty of others don't. I'm not aware of
implementations that don't have a lower limit at all, though.
Oct 16 '08 #14
On Oct 15, 5:02*pm, Adam <ne**@snowstone .org.ukwrote:
Hi,

I have a simple printf-like function:

int print(const char *format, ...)
{
* char buffer[1024];
* va_list argptr;
* int i;

* va_start(argptr , format);
* i = vsnprintf(buffe r, sizeof(buffer), format, argptr);
* va_end(argptr);

* buffer[sizeof(buffer)-1] = '\0';

* printf("%s\n",b uffer); /* this bit just for the sake of testing */

* return i;

}
You're using [v]snprintf() as a "safer [v]sprintf()", which is already
OK, but you should also take advantage of the fact that [v]snprintf()
returns the required length when you pass it zero as the size (the 2nd
argument). That will ensure that the result won't be truncated (in
this case, to 1024 characters).

int print(const char *format, ...)
{
va_list ap;

va_start(ap, format);
int len = vsnprintf(NULL, 0, format, ap); // figure out the length
va_end(ap);

char buffer[len + 1];
va_start(ap, format);
vsnprintf(buffe r, len + 1, format, ap);
va_end(ap);

printf("%s\n", buffer);

return len;
}

Sebastian

Oct 17 '08 #15
On 16 Oct, 00:50, Nate Eldredge <n...@vulcan.la nwrote:
Adam <n...@snowstone .org.ukwrites:
Hi,
I have a simple printf-like function:
int print(const char *format, ...)
{
* char buffer[1024];
* va_list argptr;
* int i;
* va_start(argptr , format);
* i = vsnprintf(buffe r, sizeof(buffer), format, argptr);
* va_end(argptr);
* buffer[sizeof(buffer)-1] = '\0';
* printf("%s\n",b uffer); /* this bit just for the sake of testing */
* return i;
}
If I call the function using something like:
char message[50];
strcpy(message, "hi there");
print("%s",mess age);
everything works, but if I do:
print(message);
it doesn't (program crashes with an abort).

I don't see a problem myself. *I took your function and added a main function:

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

/* your function */

int main(void) {
* print("%s\n", "Hello world!");
* print("Goodbye world!\n");
* return 0;

}

and it compiles and runs without problems on three different systems.
Actually, the bit I was wondering about was passing a (char *) to the
print function, rather than a literal string. I did find this page:
http://www.eskimo.com/~scs/cclass/int/sx11c.html
....which seems to suggest (in the first paragraph) this might be
wrong.
There could be something that I'm missing, though, which doesn't show up
on those systems. *Can you post a complete program that aborts, and tell
us the system and compiler you're using?
Well, the compiler is GCC. Trouble is, I can't replicate it in a
simple example (and a complex example would take me well out of
comp.lang.c territory). I though perhaps that some undefined behaviour
was causing problems in one case but not in another, but
I guess I need to look elsewhere for my problem.
Keith wrote:
This isn't your problem, but what's the purpose of [buffer[sizeof(buffer)-1] = '\0']?
Hmm, well when I originally wrote a function like this I wasn't sure
about the rules for whether it would get terminated or not and it
seemed it didn't if the incoming string was truncated. However, a
similar test now seems to reveal it does work, as you say.
Thanks,
Adam
Oct 20 '08 #16
Adam <ne**@snowstone .org.ukwrites:
[...]
Keith wrote:
>This isn't your problem, but what's the purpose of [buffer[sizeof(buffer)-1] = '\0']?
Hmm, well when I originally wrote a function like this I wasn't sure
about the rules for whether it would get terminated or not and it
seemed it didn't if the incoming string was truncated. However, a
similar test now seems to reveal it does work, as you say.
Testing doesn't prove anything. The way to confirm that the string
will be properly terminated string is to read the documentation for
the functions you're using.

If you were using a function that *isn't* guaranteed to produce a
properly terminated string, testing will very likely fail to detect
the problem; consider that uninitialized memory is often set to zero
(though that's by no means guaranteed).

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Oct 20 '08 #17
Adam wrote:
On 16 Oct, 00:50, Nate Eldredge <n...@vulcan.la nwrote:
Adam <n...@snowstone .org.ukwrites:
Hi,
I have a simple printf-like function:
int print(const char *format, ...)
{
� char buffer[1024];
� va_list argptr;
� int i;
� va_start(argptr , format);
� i = vsnprintf(buffe r, sizeof(buffer), format, argptr);
� va_end(argptr);
� buffer[sizeof(buffer)-1] = '\0';
� printf("%s\n",b uffer); /* this bit just for the sake of testing */
� return i;
}
If I call the function using something like:
char message[50];
strcpy(message, "hi there");
print("%s",mess age);
everything works, but if I do:
print(message);
it doesn't (program crashes with an abort).
I don't see a problem myself. �I took your function and added amain function:

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

/* your function */

int main(void) {
� print("%s\n", "Hello world!");
� print("Goodbye world!\n");
� return 0;

}

and it compiles and runs without problems on three different systems.

Actually, the bit I was wondering about was passing a (char *) to the
print function, rather than a literal string. I did find this page:
http://www.eskimo.com/~scs/cclass/int/sx11c.html
...which seems to suggest (in the first paragraph) this might be
wrong.
In C, the type of a string literal is char*; when used in this
contexts, (and most other contexts) "message" decays to a char* too.
Therefore, whatever issue might arise with a string literal will also
arise with "message".

The first paragraph that you refer to on that web page talks about the
integer promotions, which only apply to integer types like 'char'.
Pointer types like 'char *' remain unaffected by the integer
promotions.
There could be something that I'm missing, though, which doesn't show up
on those systems. �Can you post a complete program that aborts,and tell
us the system and compiler you're using?

Well, the compiler is GCC. Trouble is, I can't replicate it in a
simple example (and a complex example would take me well out of
comp.lang.c territory).
Start with your complicated example, and start simplifying it by
removing things. Test after each removal. When a removal causes the
problem to disappear, put it back in and remove something else. If you
do this systematically, you will either produce a minimum-size program
that demonstrates the problem which you can post to this group, no
matter how long it is; or you'll realize what the problem is. In my
experience, it's usually the second possibility that actually comes
up.
This isn't your problem, but what's the purpose of [buffer[sizeof(buffer)-1] = '\0']?
Hmm, well when I originally wrote a function like this I wasn't sure
about the rules for whether it would get terminated or not and it
seemed it didn't if the incoming string was truncated. However, a
similar test now seems to reveal it does work, as you say.
Performing a test is not a goodway to figure this out. The test will
tell you what your compiler does; it won't tell you whether this a
special case, or something you can rely on. Reading and understanding
the documentation of the vsnprintf() function is the best way. The
standard's description of vsnprintf() cross-references snprintf(). The
description of snprintf() says "a null character is written at the end
of the characters actually written into the array." The documentation
that comes with your compiler should say roughly the same thing.
Oct 20 '08 #18
On Oct 20, 10:09 pm, jameskuy...@ver izon.net wrote:
>
In C, the type of a string literal is char*; when used in this
contexts, (and most other contexts) "message" decays to a char* too.
Therefore, whatever issue might arise with a string literal will also
arise with "message".
The type of a string literal is char [n] where n is size of the string
literal.
What are you talking about? I hope I haven't took this out of context.
Oct 20 '08 #19
vipps...@gmail. com wrote:
On Oct 20, 10:09 pm, jameskuy...@ver izon.net wrote:

In C, the type of a string literal is char*; when used in this
contexts, (and most other contexts) "message" decays to a char* too.
....
The type of a string literal is char [n] where n is size of the string
literal.
What are you talking about? I hope I haven't took this out of context.
What I should have done is replace the first sentence with:

In C, in this context (and in most other contexts) both string
literals and arrays of char like "message" are converted to char*
pointers.

Oct 20 '08 #20

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

Similar topics

4
13547
by: Andrew Chalk | last post by:
I am a raw beginner to Python. I just read in "Learning Python" that assigning to a string argument inside a function does not change the string in the caller. I want an assignment in the function to alter the passed string in the caller. Is there any way to do this? For example def SafeAdd(self, Variable, Value): if self.form.has_key( Value ): Variable = self.form.value
3
4521
by: Lyn | last post by:
Hi, I have a Search input form which collects from the user a person's name. I am using LIKE with a "%" suffix in the SQL so that the user does not have to type in the full name. When they hit the Search button, a query is run to search the Person table for a match. This produces a recordset (I am using ADO). If the RecordCount is zero, they get a No Match message. If the RecordCount is 1, a DoCmd.OpenForm is performed to open the...
6
2836
by: Stuart McGraw | last post by:
I am looking for a VBA "format" or "template" function, that is, a function that takes a format string and a varying number of arguments, and substitutes the argument values into the format string as specified in the format string. For example fmt("this is $1 format string. arg2 is $2", "short", 3) would return the string "this is short format string. arg2 is 3" Now, the above is easy to write and I have done so. What I want is...
7
4366
by: al | last post by:
char s = "This string literal"; or char *s= "This string literal"; Both define a string literal. Both suppose to be read-only and not to be modified according to Standard. And both have type of "const char *". Right? But why does the compiler I am using allow s to be modified, instead of generating compile error?
23
3615
by: Nascimento | last post by:
Hello, How to I do to return a string as a result of a function. I wrote the following function: char prt_tralha(int num) { int i; char tralha;
35
2469
by: michael.casey | last post by:
The purpose of this post is to obtain the communities opinion of the usefulness, efficiency, and most importantly the correctness of this small piece of code. I thank everyone in advance for your time in considering this post, and for your comments. I wrote this function to simplify the task of combining strings using mixed sources. I often see the use of sprintf() which results in several lines of code, and more processing than really...
6
1491
by: AT | last post by:
Can someone please explain me the following: quote from documentation "Unlike other intrinsic data types, String is a reference type. When a variable of reference type is passed as an argument to a function or subroutine, a reference to the memory address where the data is stored is passed instead of the actual value of the string. " Code
232
13360
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an integer, without any junk thrown in, i.e. it must satisfy the regular expression: ^ *?+ *$ If the...
21
55637
by: phpCodeHead | last post by:
Code which should allow my constructor to accept arguments: <?php class Person { function __construct($name) { $this->name = $name; } function getName()
0
9680
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
10456
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
10230
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
10174
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
9052
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
5575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4118
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3731
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2926
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.