Hello,
Here is the program
#include stdio
int main(void)
{
const int num = 100;
int *ip;
ip = (int *)#
*ip = 200;
printf("value of num is %d(%d) \n", num, *ip);
}
Output:
value of num is 100(200)
The output says that *ip is changed and 'num' is unchanged. How is this
possible when both of them point to the same memory location? My wild guess
says that this trick is handled at the compiler level. Am I correct?
Even when the memory location is accessable and the contents changed the
'const integer' is unaffected.
Thanks
Nov 14 '05
83 3072
"Dik T. Winter" <Di********@cwi .nl> wrote in message news:<Hr******* *@cwi.nl>... In article <M8ELb.7737$sv6 .21302@attbi_s5 2> glen herrmannsfeldt <ga*@ugcs.calte ch.edu> writes: > Kevin Goodsell wrote: > > (snip) > > > My compiler did. But this is not required, and it is not always possible > > or desirable for a compiler to complain about possible undefined behavior. > > In the unix tradition there was lint, which gave all the messages > that one might possibly want to see.
How wrong you are. Many cases of undefined behaviour are not detectable. On the other hand, getting a program "lint free" could be a considerable effort; even for programs that were completely portable.
Ensuring a program is lint free is impossible.
The following is an example:
[ -------- a.c ---------- ]
#include <stdio.h>
int main(void)
{
printf("Hello world\n");
return 0;
}
[ -------- a.c ---------- ]
splint -strict a.c
Splint 3.0.1.6 --- 26 Feb 2002
a.c: (in function main)
a.c:4:5: Called procedure printf may access file system state, but globals list
does not include globals fileSystem
A called function uses internal state, but the globals list for the function
being checked does not include internalState (Use -internalglobs to inhibit
warning)
a.c:4:5: Undocumented modification of file system state possible from call to
printf: printf("Hello world\n")
report undocumented file system modifications (applies to unspecified
functions if modnomods is set) (Use -modfilesys to inhibit warning)
Finished checking --- 2 code warnings
I am not even sure what is wrong with accessing the file system
or what in the world a "file system state" is.
The warning seems to be rather bizarre and I don't even
know if it is important.
--
nethlek
Dik T. Winter wrote:
(snip)
I wrote: > In the unix tradition there was lint, which gave all the messages > that one might possibly want to see.
How wrong you are. Many cases of undefined behaviour are not detectable. On the other hand, getting a program "lint free" could be a considerable effort; even for programs that were completely portable.
I suppose that was a little bit overdoing it. I meant it in the
context of possible compiler messages. I would not want a compiler
that generated the messages that lint does. It would be too hard
to find the real error messages.
That many lint messages are for constructs that may be valid, but
can be confusing, or that it is not possible to tell.
It might have been lint that gave the warning for the =- operator.
Maybe it still does.
-- glen
Groovy hepcat user was jivin' on Thu, 8 Jan 2004 14:50:42 +0530 in
comp.lang.c.
question on const's a cool scene! Dig it! #include stdio
Wrong. Should be this:
#include <stdio.h>
int main(void) { const int num = 100; int *ip;
ip = (int *)#
Playing with fire!
*ip = 200;
I smell something burning. You just invoked undefined behaviour.
When you play with fire, you get burnt. What do you expect?
printf("value of num is %d(%d) \n", num, *ip); } Output: value of num is 100(200)
I said it before and I'll say it again. What do you expect? You
caused undefined behaviour. Anything can happen. Stand back and watch
the nasal demons eat your hard drive.
The output says that *ip is changed and 'num' is unchanged. How is this possible when both of them point to the same memory location? My wild guess
No, "both of them" do not "point to the same memory location. One
points to an object stored at a memory location, while the other is
that object and does not point.
And as for how it's possible, it's simple. The compiler determines
two things. First, it sees the const qualified definition of num, and
decides to do a simple optimisation by keeping its value in a
register. Realising that the value of this object can never change
(because it is const qualified), the resulting object code only has to
fetch its value once and keep this value in a register. And second,
the compiler determines that num must be an actual object stored in
memory someplace, because its address is taken. Now, combining these
two simple facts, the program updates the stored value of num when it
is accessed via the pointer, but the compiler still thinks num's value
cannot change, so it doesn't re-fetch this value. Thus, the old value
of num remains in the register that is being used to represent it.
When the values are used in the printf() call, the compiler fetches
the value of num from the register, as usual. But since the pointer
points at an actual location in memory, the value fetched via that
pointer is the new value that was previously stored via that pointer.
says that this trick is handled at the compiler level. Am I correct?
"Handled at the compiler level"? I have no idea what you mean by
this expression.
Even when the memory location is accessable and the contents changed the 'const integer' is unaffected.
Right.
--
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"?
Kevin Goodsell wrote: Tom St Denis wrote:
"tinybyte" <ne******@box.i t> wrote in message news:pa******** *************** *****@box.it...
You can get a much improved version of lint for you favorite unix flavor here:
http://www.splint.org
It works damn well :)
It's available for Cygwin as well [e.g. windows users].
You don't even need Cygwin. There are native Windows builds. But it is one of the packages you can choose to install with Cygwin, so this is an easy way to get it (complete with documentation, I assume).
Getting it from the main site does indeed include a bundle of
documentation, if that's the correct way to parse that sentence. I'd suggest using some caution with splint. It does catch many legitimate bugs, possible bugs and general "bad coding styles" but it also does report many things that are not invalid code. E.g.
void func(int *data) { if (data == NULL) { trap(); return; } data[0] = 1; }
Will report possible dereferencing of a NULL value [etc..]
Overall I agree with the suggestion.
It can definitely be overly paranoid (and sometimes blatantly stupid), to the point where you get so much output that it's very difficult to determine what is and is not cause for concern.
You don't need to be so diplomatic about things: It seems that plenty of
lint-like programs are downright /broken/ in some respects, and will
produce messages that indicate a less-than-complete knowledge of the
relevant Standards.
But I think you can also enable and disable specific warnings, so with some effort you should be able to come up with a reasonable set. This could be particularly nice if your compiler's warnings leave something to be desired (as they often do).
splint makes this particularly easy, in fact. Each error message comes
with three things: The short form (printed each time on messages that
are generated more than once), the long form (only printed once), and
the argument you can pass on the command line to splint to make it not
generate that warning at all (also only printed once). It's the only
reason I use splint instead of another lint, especially after a
discussion I had once here about the general intelligence of lint-like
programs. -Kevin
--
My address is yvoregnevna gjragl-guerr gjb-gubhfnaq guerr ng lnubb qbg pbz
Note: Rot13 and convert spelled-out numbers to numerical equivalents. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Jessica |
last post by:
Hi,
I have a design question. I am making a time series analysis tool.
Since I already use STL vector to represent time series, is there a
need to implement a class for the time series object? Right now I
just use
typedef vector<double>TS;
Is that enough? I feel that I am not taking advantage of the C++
|
by: CoolPint |
last post by:
While I was testing my understanding of Functioin Template features by
playing with simple function templates, I got into a problem which I
cannot understand. I would be very grateful if someone offered me a
kind explanation. TIA
Function template and specialization below works fine:
template <typename T>
T maximum (T a, T b)
{
|
by: fb |
last post by:
Hi everyone. I have the following code. It was a question out of C++
how to program. I get a warning about "possible unreachable code" in
the RunCode() function, but I don't see any problem with it...
I was hoping for a better way of exiting the case statements below. I
used exit() for "divide by zero" and "invalid instruction". I can't get
a try/catch to work. Probably from a lack of experience. I have a
fairly strong C...
|
by: Harry |
last post by:
Hi all,
I am writing a logger program which can take any datatype.
namespace recordLog {
enum Debug_Level {low, midium, high};
class L {
std::ofstream os;
Debug_Level cdl;
const Debug_Level ddl;
|
by: Rouben Rostamian |
last post by:
The main() function in the following code defines an m by n
matrix, assigns value(s) to its elements, then passes the matrix
to function foo().
For whatever it's worth, I have declared foo() so as to make
it treat its first argument as a "read-only" object, that is,
foo() can read but not alter the matrix.
I have a problem, however, with /calling/ foo. If I call
foo as foo(a,m,n), my compiler (gcc) complains about:
| |
by: JoeC |
last post by:
I am trying to design some complex objects that have quite a bit of
data. I understand most syntax but I am trying to learn how to make
better design choices. The first question is to OK or good design to
have large objects with several has-a relationship with other objects.
Second, I want my unit to have a coord struct.
struct coord{
int x;
|
by: streamkid |
last post by:
i'm a learning newbie at c++... and i have the following question...
reading some source code, i saw this:
int function(const void * one, const void * two)
{
int var1, var2;
var1 = *((int*)one);
var2 = *((int*)two);
/* sm other code here*/
}
|
by: indrawati.yahya |
last post by:
In a recent job interview, the interviewer asked me how I'd design
classes for the following problem: let's consider a hypothetical
firewall, which filters network packets by either IP address, port
number, or both. How should we design the classes to represent these
filters?
My answer was:
class FilterRule
{
|
by: Alexander Dong Back Kim |
last post by:
Dear all,
I used to use C++ programming language at all time but moved to C# and
Java. Few days ago, I restarted studying about C++ with a very
beginner's mind. I wrote a simple class and gcc couldn't compile the
class. Any hints that I'm missing?
Header File:
#ifndef __Calc_h__
|
by: fabian.lim |
last post by:
Hi,
I have a question on constant variables. In the following code
snippet, I have a function assign() that takes in an iterator to the
private variable v, the number of stuff to assign (int n), and the
information to assign (a const pointer to a class object
Vector<TYPE>.
According to the arrow below, I put a const keyword in the function.
To my knowledge, this means that all private variables in this object
|
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...
| |
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,...
|
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...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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
|
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...
| |