473,770 Members | 5,284 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Does this allocate memory?

If this is the complete program (ie, the address of the const is never
taken, only its value used) is it likely the compiler will allocate ram for
constantA or constantB? Or simply substitute the values in (as would be
required if I used the hideous, evil, much-abused #define :)

-----------

const int constantA = 10;
static const int constantB = 20;

void main()
{
for( int i=0; i<constantA ; i++ );
for( int j=0; j<constantB ; j++ );
}

----------

Thanks in advance :)

-Curt

Jul 19 '05
37 4678

Karl Heinz Buchegger wrote:

Karl Heinz Buchegger wrote:

???
There seems to be a misconception of what volatile really does.
In the above, volatile doesn't do, what you seem to think it does.


Apologies.
It was my fault. A few seconds after hitting 'send', I realized what you
are aming at. And it will work. You are right and I was wrong.

One more time: Apologies.


Sorry, but volatile *indeed* doesn't do what you seem to think it
does. Nobody knows what it does because it's totally brain-damaged
"concept".

So, you're wrong and I'm right, of course.

regards,
alexander.
Jul 19 '05 #31
On Thu, 24 Jul 2003 10:35:40 -0400, Alexander Terekhov wrote:

Karl Heinz Buchegger wrote:
Apologies.
It was my fault. A few seconds after hitting 'send', I realized what
you are aming at. And it will work. You are right and I was wrong.

No problemo, wasn't going to say anything ;)

Sorry, but volatile *indeed* doesn't do what you seem to think it does.
Nobody knows what it does because it's totally brain-damaged "concept".

So, you're wrong and I'm right, of course.

regards,
alexander.


I've bever used it myself, and without looking it up in the ARM or google
or anything, I seem to recall volitile being used to keep the compiler
from optimizing out necessary code that looks harmless, a simple example
might be a (poorly written) multithreaded program:

void thread1()
{
int i;
invokethread( thread2, &i );

i = 1;

sleep( 100 );

while( i == 2 );

..
..
..
}

void *thread2( void *arg )
{
int *p = (int *)arg;

*p = 2;

return 0;
}

--------

In this example, admittedly braindead, a clever compiler might look at
thread1 and see that a locally-scoped 'i' could not be modified by
'sleep', and the next check "while" will never succeed, and it might be
optimized out. by declaring 'i' as volatile, the compiler must honor all
references to its value.

This actally has applications in interrupt-driven device drivers, as I
say I've never had a need for it, and I could be wrong! Its been some
years since I looked up its function.

-Curt

Jul 19 '05 #32
"Jingz" <e@spam.com> wrote in message
news:pa******** *************** **********@spam .com...
On Thu, 24 Jul 2003 10:35:40 -0400, Alexander Terekhov wrote:
Sorry, but volatile *indeed* doesn't do what you seem to think it does. Nobody knows what it does because it's totally brain-damaged "concept".
So, you're wrong and I'm right, of course.

regards,
alexander.
I've bever used it myself, and without looking it up in the ARM or

google or anything, I seem to recall volitile being used to keep the compiler
from optimizing out necessary code that looks harmless, a simple example might be a (poorly written) multithreaded program:


The C++ standard doesn't care about multi-threading. Making variables
volatile will not guarantee correct behaviour in a multi-threaded
environment. Unless you know exactly what your compiler does with the
volatile specification and what that means for the execution
environment, the volitile keyword is of little or no use in most cases.

Non volatile variables may loaded at (more or less) arbitratrary times
from memory into a processor register and written back to memory at
(more or less) arbitrary times as well, in the meanwhile the value of
the value may have been changed many times without those changes being
reflected in memory. This optimization is problematic when multiple
threads access the same variable, as they essentially may operate on
their copy of the variable and don't see the changes made by the other
threads. Usually declaring a variable volatile means that the value of a
variable is loaded from memory every time it is needed, and written back
to memory every time its value is changed. However this doesn't
guarantee correct behaviour in a multi-threaded enviroment.

Example:

volatile int v=0;

void ThreadA()
{
for(int i = 0; i < 1000; ++i)
{
++v;
}
}

void ThreadB()
{
for(int i = 0; i < 1000; ++i)
{
++v;
}
}

So the question is what will be the value of 'v' when threads A and B
have completed? The answer is that the value of 'v' can be anything
between 1000 and 2000. This is because the line ++v may very well be
translated to three processor instructions:

mov ecx, [v];// Load value from memory into ecx register.
inc ecx // Increment value of ecx register
mov [v], ecx // Write value back to memory.

The problem is that a thread context switch can occure after every
processor instruction. If thread A loads the value 0 from memory into
ecx, and immediately after that instruction a context switch to thread B
occures thread B will read a 0 value for v as well. Now lets suppose
thread B can complete without a context switches to thread A. In that
case the value of variable v in memory will be 1000 at that point in
time. However when thread A continues it will still have 0 in its ecx
register, and after the first iteration of the loop in thread A the
value of v in memory will go back from 1000 to 1. Consequently when
thread A finishes the value of 'v' will be 1000. This is just one
example what may go wrong.

Moral of this story; for proper thread synchronisation you will have to
rely on the facilities offered by the platform, C++ cannot help you
here.

--
Peter van Merkerk
peter.van.merke rk(at)dse.nl

Jul 19 '05 #33

Jingz wrote:
[...]
I've bever used it myself, and without looking it up in the ARM or google
or anything, I seem to recall volitile being used to keep the compiler
from optimizing out necessary code that looks harmless, a simple example
might be a (poorly written) multithreaded program: ....


Heck. Advice: *PLONK* volatiles.

http://groups.google.com/groups?selm...1602E%40web.de
(Subject: Re: Volatile and threads.)

http://groups.google.com/groups?selm...5F41B%40web.de
(Subject: Re: Does anyone think 'volatile' is a platform-independent
way to make variable access thread safe?)

regards,
alexander.
Jul 19 '05 #34
> The C++ standard doesn't care about multi-threading. Making variables
volatile will not guarantee correct behaviour in a multi-threaded
environment. Unless you know exactly what your compiler does with the
Reading some of the other posts here I can understand why you jumped to
the conclusion that I don't know the difference between the language and
the system upon which it runs, I think you missed the point of my example.

More plainly, my point was that the 'volatile' qualifier prevents the
compiler from removing references to code that appear to have no effect,
specifically, I presented an example where the address of that variable
was known to another thread of execution.

Precicely because c++ has no concern for threads of execution, interrupt
handlers, pre-emption or any other such higher-level concepts, it must be
told- "no, I really mean check a variable multiple times even though no
code appears to change it between checks, I know better"

Your point about variables being loaded into registers at random times is
well taken, a compiler can decide to sample the value once from main RAM,
then stick it in a register and continue to test it there, I would presume
the 'volatile' qualifier would also prevent this behavior.

Moral of this story; for proper thread synchronisation you will have to
rely on the facilities offered by the platform, C++ cannot help you
here.


Absolutely, and thank you for pointing it out so clearly to anyone else
following this thread who might have also mis-interpreted my example.

-Curt

Jul 19 '05 #35
"Jingz" <e@spam.com> wrote in message
news:pa******** *************** **********@spam .com...
The C++ standard doesn't care about multi-threading. Making variables
volatile will not guarantee correct behaviour in a multi-threaded
environment. Unless you know exactly what your compiler does with the
Reading some of the other posts here I can understand why you jumped to
the conclusion that I don't know the difference between the language and
the system upon which it runs, I think you missed the point of my example.


Don't worry, I didn't make any assumptions about your knowledge, and I did
see the point of you example (the point was clear enough even for me to see
it).

The reason I responded is that your posting seemed to confirm a popular
misconception that 'volatile' qualifier would help to solve at least some
multithreading issues. It does not, period. It only gives people a false
sense of security. Misconceptions like this can lead to extremely difficult
to track down bugs. Good luck finding a unreproducable bug that shows its
ugly face about 10 times a year at totally arbitrary times!

I have written plenty of multi-threaded code, but never had any use for the
'volatile' keyword.
The 'volatile' qualifier may have its uses in very particular cases, but
that depends entirely on the platform and the compiler.
More plainly, my point was that the 'volatile' qualifier prevents the
compiler from removing references to code that appear to have no effect,
specifically, I presented an example where the address of that variable
was known to another thread of execution.

Precicely because c++ has no concern for threads of execution, interrupt
handlers, pre-emption or any other such higher-level concepts, it must be
told- "no, I really mean check a variable multiple times even though no
code appears to change it between checks, I know better"

Your point about variables being loaded into registers at random times is
well taken, a compiler can decide to sample the value once from main RAM,
then stick it in a register and continue to test it there, I would presume
the 'volatile' qualifier would also prevent this behavior.


Yes, it does force the compiler to access memory for that variable whenever
it is used or changed. But that still doesn't guarantee correct behaviour in
a multi-threaded environment. Note that the example I provided used a
volatile variable to communicate between two threads, and even in that case
it is not guaranteed it produces the correct result. Many processors cannot
directly manipulate values in memory and have to use registers to do the
actual arithmetic. So even manipulating volatile variables will typically
require several instructions to load, modify and store the variable value.
Consequently modifying a volatile variable cannot be considered to be atomic
operation, hence the 'volatile' qualifier does not guarantee correct
behaviour in a multi-threaded environment.

The funny thing with my example is that if it is compiled with an optimizing
compiler but without the 'volatile' qualifier for variable 'v', the chance
of getting the expected result might actually be higher. If 'v' isn't
volatile the compiler may replace the for loop with 'v+=1000;', which is
much less likely to be interrupted by a context switch.

--
Peter van Merkerk
peter.van.merke rk(at)dse.nl
Jul 19 '05 #36

Peter van Merkerk wrote:
[...]
The funny thing with my example is that if it is compiled with an optimizing
compiler but without the 'volatile' qualifier for variable 'v', the chance
of getting the expected result might actually be higher. If 'v' isn't
volatile the compiler may replace the for loop with 'v+=1000;', which is
much less likely to be interrupted by a context switch.


Compiler *may* replace the for loop with 'v+=1000;' even if v is
volatile. You still don't get it, I'm afraid.

regards,
alexander.
Jul 19 '05 #37

Peter van Merkerk wrote:
[...]
Though it doesn't prove anything, on all compilers I ever tried, the
volatile keyword does actually affect the generated code, but not in a way
it is of any use in a multi-threaded environment. If you are right, I wonder
why compilers bother doing something with the 'volatile' keyword instead of
treating it the same way they typically do with the 'register' keyword, i.e.
ignore it.


Well, in this case, the reason is nothing but "stupidity rules", I
think. As I said, volatile is totally brain-damaged.

http://groups.google.com/groups?thre...1D2D6%40web.de
http://groups.google.com/groups?selm...1602E%40web.de

regards,
alexander.
Jul 19 '05 #38

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

Similar topics

4
3672
by: Alan Gifford | last post by:
I wrote a program to make sure that new would throw a bad_alloc exception if more memory was requested than was available. On my system, new allocates up to 2931 MBs of memory (I don't have that much, not even with swap) before throwing an exception. When the program tries to fill in the allocated memory with data, it is killed after using up the available memory. Does anyone know why the exception is not being thrown until well after...
4
2591
by: Franklin Lee | last post by:
Hi All, I use new to allocate some memory,even I doesn't use delete to release them. When my Application exit, OS will release them. Am I right? If I'm right, how about Thread especally on Solaries OS? This means that I use new to allocate memory in one Thread and doesn't use delete to release them.
9
3735
by: R.Z. | last post by:
i was wondering whether it pays off in terms of memory use to maintain lots of empty deques (it would be convenient for my algorithms but memory use is more important). and does the size of a deque depends on the size of its members even if the deque is empty? is there at all a way to check out how much memory my deque occupies? i've read that the sizeof operator cannot be used with dynamically allocated arrays so i figured it wouldn't give...
74
4053
by: Suyog_Linux | last post by:
I wish to know how the free()function knows how much memory to be freed as we only give pointer to allocated memory as an argument to free(). Does system use an internal variable to store allocated memory when we use malloc(). Plz help......
6
2316
by: lovecreatesbeauty | last post by:
Hello experts, 1. Does C guarantee the data layout of the memory allocated by malloc function on the heap. I mean, for example, if I allocate a array of 100 elements of structure, can I always reference a correct/valid structure member upon that allocated memory? If I allocate memory, for example like this way:
3
1797
by: Nadav | last post by:
Hi, I am writing a mixed mode application, I have a mixed mode Assembly manipulating a managed byte array, to access this array in unmanaged code I '__pin' the array, As I understand, pining an object guarantee that it will not be collected by the GC ( by increasing it's refcount or so ), Taking that in mind, looking at the code generated by the compiler I can't see anything taking care of the GC refcount... following is the pinned variable...
5
4716
by: Allen | last post by:
I wrote many classes. In a class, there is a member variable which is declared as char szMTreeBuf. On both Windows XP and VxWorks, it cannot work. Then I try to declare the member variable as static char szMTreeBuf, it can work again. But when add some other function codes, it cannot run normally. I modify the class delearation, and change szMTreeBuf member variable to be local variable. Again it can run now. Why does C++ program run...
5
8092
by: mkaushik | last post by:
Hi everyone, Im just starting out with C++, and am curious to know how "delete <pointer>", knows about the number of memory locations to free. I read somewhere that delete frees up space assigned to <pointerby "new". Does "new" create a list of pointer names and the size of the memory array they point to? I also read that some compilers may store the number of consec mem locations a pointer points to, just before the first data...
9
8179
by: rohits123 | last post by:
I have an overload delete operator as below ////////////////////////////////// void operator delete(void* mem,int head_type) { mmHead local_Head = CPRMemory::GetMemoryHead(head_type); mmFree(&local_Head,(char *)mem); CPRMemory::SetMemoryHeadAs(local_Head,head_type); } ///////////////////// void* operator new(size_t sz, int head_Type) {
0
9591
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
9425
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
10225
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
8880
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
6676
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
5449
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3969
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
3573
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2816
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.