473,698 Members | 2,300 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

is casting a variadic function to a non-variadic one legal?

Hi,

I have a program which had a little function that always returned TRUE,
it looked like this:

int
always_true_fun ction (void *dummy, ...)
{
return 1;
}

Now, at one point I was calling this via a function pointer that was
defined without the varargs, like this:

typedef int (*testfunc) (void *dummy);

int
main (int argc, char **argv)
{
testfunc f = (testfunc) always_true_fun ction;
if (f (NULL))
return 0;
return 1;
}

This all worked fine up until recently, when I heard from one user who was
trying to run the program on AMD64 was getting very mysterious segfaults.

On my machine (i386, gcc 3.3.2), the above test program works fine. On
his machine (AMD64, gcc 3.3.2 + propolice patch), it segfaults.

It turned out I didn't actually need the varargs, but I'm curious - who is
at fault here? Is my code wrong, or is his gcc broken?

Nov 14 '05 #1
2 1569
Colin Walters <wa*****@cis.oh io-state.edu> writes:
I have a program which had a little function that always returned TRUE,
it looked like this:

int
always_true_fun ction (void *dummy, ...)
{
return 1;
}

Now, at one point I was calling this via a function pointer that was
defined without the varargs, like this:

typedef int (*testfunc) (void *dummy);


That's undefined behavior. You're not supposed to call a varargs
function through a non-varargs prototype.
--
int main(void){char p[]="ABCDEFGHIJKLM NOPQRSTUVWXYZab cdefghijklmnopq rstuvwxyz.\
\n",*q="kl BIcNBFr.NKEzjwC IxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+= strchr(p,*q++)-p;if(i>=(int)si zeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #2
In article <news:pa******* *************** ******@cis.ohio-state.edu>
Colin Walters <wa*****@cis.oh io-state.edu> writes:
int
always_true_fu nction (void *dummy, ...)
{
return 1;
}

Now, at one point I was calling this via a function pointer that was
defined without the varargs, like this:

typedef int (*testfunc) (void *dummy);

int
main (int argc, char **argv)
{
testfunc f = (testfunc) always_true_fun ction;
if (f (NULL))
return 0;
return 1;
}

This all worked fine up until recently, when I heard from one user who was
trying to run the program on AMD64 was getting very mysterious segfaults.

On my machine (i386, gcc 3.3.2), the above test program works fine. On
his machine (AMD64, gcc 3.3.2 + propolice patch), it segfaults.

It turned out I didn't actually need the varargs, but I'm curious - who is
at fault here? Is my code wrong, or is his gcc broken?


Your code is technically wrong (or "illegal" or any other number of
words that do not really carry the right meaning). Specifically,
the call:

f(NULL)

invokes undefined behavior by calling a function through a pointer
that has the wrong type. In this case, the AMD64 system probably
uses different call sequences for "varying arguments" vs "fixed
arguments", but in principle this can even happen if you call a
function whose actual type is (e.g.) void(void *) instead of
int(void *).

You can correct the call (without any structural changes to the
code itself, such as changing the name and/or type of
always_true_fun ction()) in at least two ways:

if (((int (*)(void *, ...))f)(NULL)) ...

will convert the function pointer stored in "f" back to the correct
type, then (correctly) call the actual function always_true_fun ction();
or you can insert an intermediate function:

int always_true_fun ction(void *dummy, ...) { return 1; }

int adapter_for_alw ays_true_functi on(void *passthrough) {
return always_true_fun ction(passthrou gh);
}
...
testfunc f = adapter_for_alw ays_true_functi on;

The adapter serves as a sort of "pipe fitting" to connect the
"two-inch pipeline" (varying argument function, in this case)
to the "3/4-inch hose" (non-varying call).

The cast method works, but requires great care -- you must always
match the converted-to type just before the call to the actual
type of the target function. This may well defeat the entire
purpose of using function pointers in the first place, so the
adapter method is more general.

It also acts as a kind of lesson: any time you have a pointer cast
in C code, be suspicious. If there is a pointer-cast-free way to
rewrite the code, that second version probably has fewer bugs. :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #3

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

Similar topics

4
3467
by: Jacob Jensen | last post by:
This question has probably been asked a million time, but here it comes again. I want to learn the difference between the three type cast operators: static_cast, reinterpret_cast, dynamic_cast. A good way to do this is by example. So I will give an example and please tell me what you think: I have a base class A with a virtual destructor, and a class B that is it inherits publicly from A and defines som extra stuff.
16
2433
by: He Shiming | last post by:
Hi, I'm having a little bit of trouble regarding pointer casting in my program. I don't understand why the following two cases produce different results. Case 1: IInterface *pInterface = new CImplementation(); pInterface->Method(); Case 2:
231
23135
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be correct form?
14
2458
by: Enrico `Trippo' Porreca | last post by:
Given: typedef struct Node Node; struct Node { void *obj; Node *next; }; typedef struct Stack Stack; struct Stack {
44
2215
by: Agoston Bejo | last post by:
What happens exactly when I do the following: struct A { int i; string j; A() {} }; void f(A& a) { cout << a.i << endl;
8
357
by: Yin99 | last post by:
I have the following code (Mammal base class, Dog inherits from Mammal): Dog *spot= new Dog; spot->Speak(); Mammal *fido = dynamic_cast<Mammal*>(spot); fido->Speak(); Dog *bandit = dynamic_cast<Dog*>(fido); bandit->Speak(); I would expect the output:
3
2763
by: Tigger | last post by:
I have an object which could be compared to a DataTable/List which I am trying to genericify. I've spent about a day so far in refactoring and in the process gone through some hoops and hit some dead ends. I'm posting this to get some feedback on wether I'm going in the right direction, and at the same time hopefully save others from going through the process.
5
5925
by: brekehan | last post by:
I've always been a little sketchy on the differences between static, dynamic, and reinterpret casting. I am looking to clean up the following block by using C++ casting instead of the C style casting. from what I am reading, I should use reinterpret cast in this situation, is that correct? Why does static and dynamic casting fail me? // please excuse the windows types, it is necessary in this code, // but the question remains C++ related
28
16448
by: Peter Olcott | last post by:
I want to make a generic interface between a scripting language and native code, the native code and the interpreter will both be written in C++. The interpreter will probably be implemented as a subset of C/C++, thus will have the same syntax as C/C++. Somehow the interpreted code must be able to store generic function pointers because there is no way for the interpreter to know every possible function signature in advance. I was...
5
3906
by: jason.cipriani | last post by:
There have been some recent threads about casting pointers to and from void* that have me rethinking some of my usual practices. I have a couple of questions. 1. What is the purpose of C++'s static_cast<>? In other words, is there any real difference between statements like (with non-pointer types): double a = 3.4; int b = (int)a; // <--- this
0
8676
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
9161
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
9029
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
8897
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,...
1
6522
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
5860
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();...
0
4370
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
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2332
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.