473,669 Members | 2,504 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Type safety


In the article http://en.wikipedia.org/wiki/Type_safety

it is written as

The archetypal type-unsafe language is C because (for example) it is
possible for an integer to be viewed as a function pointer, which can
then be jumped to and executed, causing errors such as segmentation
faults, or (more insidiously) silent failures.

Even though the semantics of the C language explicitly allow for these
violations of the type system (indeed, it can be critical for the
performance of operating systems to be written in type-unsafe
languages) the language never defines what should happen when,
for example, a floating-point value is treated as a pointer.

now my question is can anybody give examples/explanations for this

Feb 24 '06 #1
18 2148
El Fri, 24 Feb 2006 09:20:28 -0800, aarklon escribió:

Even though the semantics of the C language explicitly allow for these
violations of the type system (indeed, it can be critical for the
performance of operating systems to be written in type-unsafe
languages) the language never defines what should happen when,
for example, a floating-point value is treated as a pointer.

now my question is can anybody give examples/explanations for this


int main()
{
int a = 0xFFFFFF ;

void (*p)() = (void(*)()) a;
p();

return 0;
}

Feb 24 '06 #2
aa*****@gmail.c om wrote:
In the article http://en.wikipedia.org/wiki/Type_safety

it is written as

The archetypal type-unsafe language is C because (for example) it is
possible for an integer to be viewed as a function pointer, which can
then be jumped to and executed, causing errors such as segmentation
faults, or (more insidiously) silent failures.

Even though the semantics of the C language explicitly allow for these
violations of the type system (indeed, it can be critical for the
performance of operating systems to be written in type-unsafe
languages) the language never defines what should happen when,
for example, a floating-point value is treated as a pointer.

now my question is can anybody give examples/explanations for this


Well, the article is a bit misleading. For an unprepared reader it might
create an impression of C language allowing implicit use of an integer
value in a function pointer context, which is not the case. In many
cases one can definitely work around the C type-control system without
using explicit cast (for example, but relying on the implicit "to void*"
and "from void*" pointer conversions), but it is normally not a one-step
process.

The truth is C language merely provides certain means for performing
these violations of the type system. Using these means in the program
still requires a conscious effort from the user in most cases,
especially when it comes to mixing values from the realm of "data" and
values from the realm of "code" (as in the above "integer as function
pointer" example).

--
Best regards,
Andrey Tarasevich
Feb 24 '06 #3
aa*****@gmail.c om writes:
In the article http://en.wikipedia.org/wiki/Type_safety

it is written as

The archetypal type-unsafe language is C because (for example) it is
possible for an integer to be viewed as a function pointer, which can
then be jumped to and executed, causing errors such as segmentation
faults, or (more insidiously) silent failures.

Even though the semantics of the C language explicitly allow for these
violations of the type system (indeed, it can be critical for the
performance of operating systems to be written in type-unsafe
languages) the language never defines what should happen when,
for example, a floating-point value is treated as a pointer.


This is largely nonsense. It is not possible to treat an integer as a
function pointer unless you *explicitly* convert it (the result of the
conversion is implementation-defined). The language doesn't allow
conversions from floating-point to poitner types, either implicitly or
explicitly.

--
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 24 '06 #4
On 2006-02-24, Andrey Tarasevich <an************ **@hotmail.com> wrote:
aa*****@gmail.c om wrote:
In the article http://en.wikipedia.org/wiki/Type_safety

it is written as

The archetypal type-unsafe language is C because (for example) it is
possible for an integer to be viewed as a function pointer, which can
then be jumped to and executed, causing errors such as segmentation
faults, or (more insidiously) silent failures.

Even though the semantics of the C language explicitly allow for these
violations of the type system (indeed, it can be critical for the
performance of operating systems to be written in type-unsafe
languages) the language never defines what should happen when,
for example, a floating-point value is treated as a pointer.

now my question is can anybody give examples/explanations for this


Well, the article is a bit misleading. For an unprepared reader it might
create an impression of C language allowing implicit use of an integer
value in a function pointer context, which is not the case. In many
cases one can definitely work around the C type-control system without
using explicit cast (for example, but relying on the implicit "to void*"
and "from void*" pointer conversions), but it is normally not a one-step
process.

The truth is C language merely provides certain means for performing
these violations of the type system. Using these means in the program
still requires a conscious effort from the user in most cases,
especially when it comes to mixing values from the realm of "data" and
values from the realm of "code" (as in the above "integer as function
pointer" example).


Yeah - And _especially_ in that case, you can't do it by accident - In
fact, it requires syntax that I had to look up: ((int(*)())42)( ) - and
none of those parentheses are redundant - leave out any pair and it
wont' compile. [well, if you leave out the rightmost pair, it simply
won't attempt to make a function call, i guess] That amount of required
effort to get it to work certainly requires some level of intent.
Feb 24 '06 #5
> The language doesn't allow conversions from floating-point to poitner types, either implicitly or explicitly.

What?

float x = 1.0f;
void *p = *((void**)&x);

Feb 25 '06 #6
ge**********@gm ail.com writes:
The language doesn't allow conversions from floating-point to
poitner types, either implicitly or explicitly.


What?

float x = 1.0f;
void *p = *((void**)&x);


There's no conversion from a floating-point to pointer type
there. There's a conversion from pointer-to-float type to
pointer-to-pointer-to-void type. Dereferencing that pointer
doesn't cause a conversion. Typically, it causes
reinterpretatio n of bits, but its effect is formally undefined as
stated by C99 6.5 "Expression s":

7 An object shall have its stored value accessed only by an
lvalue expression that has one of the following types:73)
- a type compatible with the effective type of the object,
- a qualified version of a type compatible with the
effective type of the object,
- a type that is the signed or unsigned type corresponding
to the effective type of the object,
- a type that is the signed or unsigned type corresponding
to a qualified version of the effective type of the
object,
- an aggregate or union type that includes one of the
aforementioned types among its members (including,
recursively, a member of a subaggregate or contained
union), or
- a character type.

--
"IMO, Perl is an excellent language to break your teeth on"
--Micah Cowan
Feb 25 '06 #7

"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org...
aa*****@gmail.c om writes:
In the article http://en.wikipedia.org/wiki/Type_safety

it is written as

The archetypal type-unsafe language is C because (for example) it is
possible for an integer to be viewed as a function pointer, which can
then be jumped to and executed, causing errors such as segmentation
faults, or (more insidiously) silent failures.

Even though the semantics of the C language explicitly allow for these
violations of the type system (indeed, it can be critical for the
performance of operating systems to be written in type-unsafe
languages) the language never defines what should happen when,
for example, a floating-point value is treated as a pointer.
This is largely nonsense. It is not possible to treat an integer as a
function pointer unless you *explicitly* convert it (the result of the
conversion is implementation-defined). The language doesn't allow
conversions from floating-point to poitner types, either implicitly or
explicitly.

One of the design decisions in C was to allow the programmer to examine the
bit representation of data in memory.
It is an inherent property of a digital computer that the bits of any type
can be reinterpreted as any other type.
C does have a few weak protections against the programmer doing this
inadvertently, but they are fairly easy to circumvent. Often it is a good
idea.

For instance, if I know that on my machine ROM routines are from addresses
0x8000 upwards, then by examining the bits of a function pointer I can tell
if it points to a function in RAM or in ROM. That might be useful to know.

--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $6.90 paper, available www.lulu.com

Feb 25 '06 #8

aa*****@gmail.c om wrote:
In the article http://en.wikipedia.org/wiki/Type_safety

it is written as

The archetypal type-unsafe language is C because (for example) it is
possible for an integer to be viewed as a function pointer, which can
then be jumped to and executed, causing errors such as segmentation
faults, or (more insidiously) silent failures.

Even though the semantics of the C language explicitly allow for these
violations of the type system (indeed, it can be critical for the
performance of operating systems to be written in type-unsafe
languages) the language never defines what should happen when,
for example, a floating-point value is treated as a pointer.

now my question is can anybody give examples/explanations for this


Feb 25 '06 #9

"Jordan Abel" <ra*******@gmai l.com> wrote in message
news:sl******** *************** @random.yi.org. ..
On 2006-02-24, Andrey Tarasevich <an************ **@hotmail.com> wrote:
aa*****@gmail.c om wrote:
In the article http://en.wikipedia.org/wiki/Type_safety

it is written as

The archetypal type-unsafe language is C because (for example) it is
possible for an integer to be viewed as a function pointer, which can
then be jumped to and executed, causing errors such as segmentation
faults, or (more insidiously) silent failures.

Even though the semantics of the C language explicitly allow for these
violations of the type system (indeed, it can be critical for the
performance of operating systems to be written in type-unsafe
languages) the language never defines what should happen when,
for example, a floating-point value is treated as a pointer.

now my question is can anybody give examples/explanations for this


Well, the article is a bit misleading. For an unprepared reader it might
create an impression of C language allowing implicit use of an integer
value in a function pointer context, which is not the case. In many
cases one can definitely work around the C type-control system without
using explicit cast (for example, but relying on the implicit "to void*"
and "from void*" pointer conversions), but it is normally not a one-step
process.

The truth is C language merely provides certain means for performing
these violations of the type system. Using these means in the program
still requires a conscious effort from the user in most cases,
especially when it comes to mixing values from the realm of "data" and
values from the realm of "code" (as in the above "integer as function
pointer" example).


Yeah - And _especially_ in that case, you can't do it by accident - In
fact, it requires syntax that I had to look up: ((int(*)())42)( ) - and
none of those parentheses are redundant - leave out any pair and it
wont' compile. [well, if you leave out the rightmost pair, it simply
won't attempt to make a function call, i guess] That amount of required
effort to get it to work certainly requires some level of intent.

But the easy way to treat an integer as a function pointer is to run off the
end of an array, and thus write an integer where a function pointer is
supposed to be.

It's not really about what the standard authorises, it's about what
compilers are able or unable to prevent, by virtue of the language design
and syntax. Strictly conforming C is necessarily type-safe, but the
compiler can't check that code is strictly conforming. In code that's
merely intended to be C, another very easy way to implicitly treat an
integer as a pointer, for instance, is to forget an & when calling scanf.

Undefined behaviour of course, but the point of type safety would be to get
good undefined behaviour -- compilation error or at worst a run-time trap --
rather than bad undefined behaviour.
To get the kind of type safety defined in the article, which comes from an
abstract computer-science perspective, you would have to prevent buffer
overruns, prevent reaching the end of a non-void function, prevent reading
of uninitialised data, keep track of the type associated with dynamic
storage, eliminate variadic functions, etc etc etc.

There are good reasons why C doesn't do this stuff. This is why we like it.
But a few dodgy casts aren't the beginning of C's lack of type safety
(unless you have a much narrower definition of type safety) -- they're just
extras thrown in on the grounds that it's already hopeless so it hardly
matters.
To go back to the OPs request for an example, here's one:

#include <math.h>
struct st {
double x[1];
double (*func)(double) ;
};
int main (void) {
struct st s;
s.func = sqrt;
s.x[0] = 1.0;
s.x[1] = 33.7; /* bad */
(void)s.func(s. x[0]);
return 0;
}

By writing off the end of the array, I've probably scribbled over the
function pointer, which I then call through, regardless.
Gcc -ansi -pedantic -Wall compiles this without warnings, and there's no
guarantee that the run-time error will be trapped before anything bad
happens.

Granted a smart-enough compiler could catch this simple example, but a more
elaborate example involving multiple translation units and/or run-time
control flow would be essentially uncatchable.

Not earth-shattering news of course, but it's a very general article, and
isn't aiming to tackle the subtleties.

--
RSH


Feb 25 '06 #10

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

Similar topics

12
2057
by: Aaron Watters | last post by:
I'm doing a heart/lung bypass procedure on a largish Python program at the moment and it prompted the thought that the methodology I'm using would be absolutely impossible with a more "type safe" environment like C++, C#, java, ML etcetera. Basically I'm ripping apart the organs and sewing them back together, testing all the while and the majority of the program at the moment makes no sense in a type safe world... Nevertheless, since...
2
2270
by: Steve Jorgensen | last post by:
I frequently find myself wanting to use class abstraction in VB/VBA code, and frankly, with the tacked-on class support in VB/VBA, there are some problems with trying to do that and have any type-safety as well. I thought I would share some of what I've come to think about this after dealing with it several times of late. First, an example. Let's say I have several classes, each with a string property called Name, and I have several...
2
2437
by: Dave | last post by:
Hello all, I am creating a linked list implementation which will be used in a number of contexts. As a result, I am defining its value node as type (void *). I hope to pass something in to its "constructor" so that I will be able to manipulate my list without the need for constant casting; some sort of runtime type-safety mechanism. For example, I want a linked lists of ints. I want to be able to say:
4
14123
by: NotYetaNurd | last post by:
Hi all, I read that delegates are type safe and Functional pointers are not!!... in this context what does type safety mean? can anyone of you throw some light on it regards, ...
3
1844
by: karthick.ramachandran | last post by:
Hi, I was just reading this article http://www.netobjectives.com/resources/downloads/Best_Practices_CSharp_Delegates.pdf In which the author had mentioned <quote> Delegates would appear to be type safe. The compiler will not allow you
27
4321
by: Noah Roberts | last post by:
What steps do people take to make sure that when dealing with C API callback functions that you do the appropriate reinterpret_cast<>? For instance, today I ran into a situation in which the wrong type was the target of a cast. Of course with a reinterpret_cast nothing complains until the UB bites you in the ass. It seems to me that there ought to be a way to deal with these kinds of functions yet still retain some semblance of type...
10
2591
by: Yevgen Muntyan | last post by:
Consider the following macro: #define ALLOCIT(Type) ((Type*) malloc (sizeof (Type))) The intent is to wrap raw memory allocation of N bytes into a macro which returns allocated chunk of memory to be used as a Type structure. The background: I was beaten many times (it surely is not my exclusive experience) by functions which return and accept void*. There are such functions,
21
3606
by: Chad | last post by:
Okay, so like recently the whole idea of using a Union in C finally sunk into my skull. Seriously, I think it probably took me 2 years to catch on what a Union really is. Belated, I mentioned this too my ultra smart friend who just quit working as a CTO of a wireless company so he go complete his PhD in particle physics. Anyhow he mentioned that Unions in C are not typesafe. Now, how is it possible to violate type safety in Unions? ...
2
13385
by: hcarlens | last post by:
hey guys, I'm doing a small project which does some basic encryption and decryption, but I'm very new to Java and Eclipse is showing safety warnings but I have no idea what they mean or how I fix them. Here is the part of the code that's causing the problem: String AlphArray = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}; ArrayList<String> Alphabet = new...
0
8383
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
8895
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
8809
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
8588
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
8658
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
6210
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
5682
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
4386
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1788
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.