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 3077 rl*@hoekstra-uitgeverij.nl (Richard Bos) writes: "Frane Roje" <frane.roje(d*e lete*)@st.hinet .hr> wrote: But if I use a char* p="test"; In that case the computer will allocate some space for the array, right?
Wrong. It will put a (unwritable!) string constant somewhere in memory, and then make p point to it. The string constant being unwritable is significant - you've been writing through that pointer in this thread, and you cannot reliably do so if p points to a string constant.
To clarify: Writing to the memory allocated for a string literal
invokes undefined behavior. It may happen to "work" on some
implementations . (It's defined that way for historical reasons.)
--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
tinybyte <ne******@box.i t> wrote: On Thu, 08 Jan 2004 20:57:44 +0000, Kevin Goodsell wrote: You seem to be having a very difficult time with the notion of undefined behavior. Look at the Standard's definition of it:
I don't have any difficulties. I am aware of it since the beginning.
All the same, you seem to have difficulties accepting its implications. Yes. The code is broken. You can establish this fact by referring to the standard.
If the code is broken, why the compiler didn't told it to me?
Imprimis, because the code is broken in a way that cannot always be
detected. It can simply be detected in this case, but there are
fundamental computational reasons why it isn't always possible whether a
certain pointer points at a const object or not. That's why this is
undefined behaviour, and not a constraint violation.
Secundis, because even if the compiler _had_ normally been able to
detect this instance and would normally have warned you, you have
explicitly told it to shut its mouth and get on with the compilation.
The cast effectively says "trust me, it may look like I'm being an
idiot, but I know what I'm doing". That this is, in this case, not quite
true is not something the compiler can detect.
Richard
tinybyte <ne******@box.i t> wrote: On Thu, 08 Jan 2004 14:31:51 +0000, Dik T. Winter wrote: No that is not inconsistent. The address *must* remain the same. The question is: "must the compiler look at that address to see what is there?" The answer to that question is *no* if the variable is declared to be const, because the compiler is allowed to assume that the value is not changed.
The compiler is allowed to assume that the value it's not changed, but sometimes it is changed, sometimes not, depends on optimization. This is inconsistent behavior for me, and in C programming this should not be ALLOWED. That is all I'm talking about.
It has always been a prime advantage of C that its creators and Standard
Committee have considered efficient behaviour of correct code more
important than consistent behaviour of incorrect code, and I, for one,
am glad that this is the case - it is one of C's properties that endears
it to me.
Richard
On Thu, 08 Jan 2004 16:27:34 -0500, Arthur J. O'Dwyer wrote: That's a noble goal. You'll see, if you stick around (which I hope you will), that many of the c.l.c "regulars" have anecdotes they've
I'll stick around here, it's a valuable resource a C (wannabe?) programmer
simply can't miss.
But comp.lang.c is not the place to learn them. In c.l.c people
This is the real thing I missed. This is not the place :)
But once you *have* expanded your knowledge base, please don't hesitate to use that knowledge wisely in this newsgroup or anywhere else.
Be sure I will!
That would be incredibly annoying, taken as a real goal. I don't
[snip] and I don't think you really want that, either. (Possible signed integer overflow in the expression 'a+1', just FYI.)
Thanks for the info, and yes, you're right, I don't want such a thing.
not. That's a result of the Halting Problem, which you can Google for, if you're interested in the theory behind all this.
Thanks for the hint. I didn't know of this decision problem. And yes,
I am interested in the theory behind, since it helps a lot in avoiding
dead ends :) I was into one...
Final note: Lest my tone sound a bit *too* fatalistic, remember that you can always ask here as to "Why is such-and-such undefined behavior?" and you'll be sure to get plenty of interesting answers.
I already got many, but I'm sure I can get even more (maybe on other
topics :)
I hope you'll keep up the learning.
Sure I'll be!
Many thanks Arthur.
Daniele
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.
DESCRIPTION
lint attempts to detect features of the named C program
files that are likely to be bugs, to be non-portable, or
to be wasteful. It also performs stricter type checking
then does the C compiler. (snip)
Among the possible problems that are currently noted are
unreachable statements, loops not entered at the top,
variables declared and not used, and logical expressions
with constant values. Function calls are checked for
inconsistencies , such as calls to functions that return
values in some places and not in others, functions called
with varying numbers of arguments, function calls that pass
arguments of a type other than the type the function expects
to receive, functions whose values are not used, and calls to
functions not returning values that use the non-existent
return value of the function.
(snip)
Some of those functions have been moved into compilers, but
maybe not all. Many messages are just too tiring to see at
each compilation, but it is nice to be able to check for them
once in a while.
Also, I believe that when given multiple files to check, lint does
more checks between files than would be done by compilers.
-- glen
user wrote: Hello,
Here is the program:
cat main.c
#include <stdio.h>
int main(int argc, char* argv[]) {
const int num = 100;
int *ip = (int*)#
*ip = 200;
printf("value of num is %d(%d) \n", num, *ip);
return 0;
}
gcc -Wall -std=c99 -pedantic -O2 -o main main.c ./main
value of num is 200(200)
On Fri, 09 Jan 2004 20:27:28 +0000, glen herrmannsfeldt wrote: In the unix tradition there was lint, which gave all the messages that one might possibly want to see.
You can get a much improved version of lint for you favorite unix flavor
here: http://www.splint.org
It works damn well :)
Bye
Daniele
"tinybyte" <ne******@box.i t> wrote in message
news:pa******** *************** *****@box.it... On Fri, 09 Jan 2004 20:27:28 +0000, glen herrmannsfeldt wrote:
In the unix tradition there was lint, which gave all the messages that one might possibly want to see.
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].
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.
Tom
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). 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. 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).
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
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.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/ 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: 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: 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...
|
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...
|
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...
|
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: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |