473,772 Members | 2,424 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Memory Allocation

72 New Member
Hello,

I may be remembering incorrectly, but I'm sure that in C++ you could declare two variables of the same name where the second declaration is within it's own code block. E.g.

Expand|Select|Wrap|Line Numbers
  1. void myfunction()
  2. {
  3.   int x = 5;
  4.  
  5.   //some code
  6.  
  7.   {
  8.     int x = 3;
  9.  
  10.     //print x
  11.   }
  12.  
  13.   //print x
  14. }
  15.  
In this case, the first time x is printed, it will refer to the x declared within the inner block, and the second time it will refer to the x in the outer block.

If this is correct, my question refers to the compiler and stack allocation.

I found out the other day that Java allocates memory for all local variables within a function block, regardless of whether the code actually reaches those declarations. Apparently, this is to make the compiler/runtime easier to code and manage. I'm assuming this is the reason you can not have a situation similar to the above code example in Java, as you would have two local variables by the same reference being allocated to the stack at the same time.

I wondered if this was the way all languages handled memory allocation. If this is the case in C++, my question is how does C++ allow two variables to be allocated to the same named reference within a function block? Does C++ allocate to the stack each time it enters any kind of code block? Or do pseudo/mask references get used, whereby the first x is internally considered as x1 and the second as x2?

Or something...

I have not a lot of knowledge on this area of coding, but it's something I've recently started wondering about for the purposes of memory optimization in my coding.

Regards,
Rob.
Feb 12 '08 #1
5 1566
weaknessforcats
9,208 Recognized Expert Moderator Expert
In C++, the operative word is stack.

That means as variables are encountered they are added to the stack. Only in C are all of the variables created on the stack at the beginning ofr the function.


C has a very simple stack frame where these variables are placed. The C++ version allows you do add to the stack frame as the function progresses. Exactly how this is done is left to the compiler writer. It could be your C++ compiler works just like your Java example but it is not required to do so.
Feb 12 '08 #2
peridian
72 New Member
Ahh, cool.

I had always done my coding on the understanding of memory being allocated to the stack as the declarations were encountered, so you can imagine my surprise when I found out about Java.

Interesting that C does it the same way as well, that's a useful tip.

Would it be fair to say that the majority of compilers do it as we have said for C++, but that it is dependant upon the compiler implementation? I.e. some compilers may do it the same as C and Java, but most don't.

Regards,
Rob.
Feb 13 '08 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
I have no idea what the common stack implementation is.

As a programmer, I just follow the scoping rules and let the compiler generate the proper code.

Also, I don't believe Java has a problem with two variables of the same name so long as they are in different scopes.
Feb 13 '08 #4
peridian
72 New Member
Fair enough.

With regard to Java, it definitely does (or at least in 1.6) have a problem with duplicate variable names within the same function block, even if in separate scope. The below is an example of the compiler message you get:

Exception in thread "main" java.lang.Error : Unresolved compilation problem:
Duplicate local variable results


Thanks for the info.

Rob.
Feb 14 '08 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
If that's reaaly true, then that is one big hole in Java. Big enough to prevent me from ever considering it for a real application.
Feb 14 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

6
8213
by: chris | last post by:
Hi all, I need to know, what is the difference between dynamic memory allocation, and stack allocation ? 1. If I have a class named DestinationAddress, when should I use dynamic memory allocation to create object of that class ? 2. If it says "dynamic memory allocation", is it mean the following code : DestinationAddress* dest = new DestinationAddress(); // code 1
4
6770
by: PaulR | last post by:
Hi, We have a Server running SLES 8 and 3GB memory, with 1 DB2 instance and 2 active Databases. General info... DB2level = "DB2 v8.1.0.72", "s040914", "MI00086", and FixPak "7" uname -a = Linux galahad 2.4.19-64GB-SMP #1 SMP /etc/sysctl.conf kernel.shmmax=268435456
74
4698
by: ballpointpenthief | last post by:
If I have malloc()'ed a pointer and want to read from it as if it were an array, I need to know that I won't be reading past the last index. If this is a pointer to a pointer, a common technique seems to be setting a NULL pointer to the end of the list, and here we know that the allocated memory has been exhausted. All good. When this is a pointer to another type, say int, I could have a variable that records how much memory is being...
62
17856
by: ivan.leben | last post by:
How can I really delete a preloaded image from memory/disk cache? Let's say I preload an image by creating an Image object and setting its src attribute to desired URL: var img = new Image(); img.src = ; Then I use the image a few more times by adding it into an Array object:
66
3642
by: Johan Tibell | last post by:
I've written a piece of code that uses sockets a lot (I know that sockets aren't portable C, this is not a question about sockets per se). Much of my code ended up looking like this: if (function(socket, args) == -1) { perror("function"); exit(EXIT_FAILURE); } I feel that the ifs destroy the readability of my code. Would it be
24
19094
by: Ken | last post by:
In C programming, I want to know in what situations we should use static memory allocation instead of dynamic memory allocation. My understanding is that static memory allocation like using array is faster than malloc, but dynamic memory allocation is more flexible. Please comment... thanks.
1
7976
by: Peterwkc | last post by:
Hello all expert, i have two program which make me desperate bu after i have noticed the forum, my future is become brightness back. By the way, my problem is like this i the first program was compiled and run without any erros but the second program has a run time error when the function return from allocate and the ptr become NULL. How to fixed this? Second Program: /* Best Method to allocate memory for 2D Array because it's ...
34
2582
by: jacob navia | last post by:
Suppose that you have a module that always allocates memory without ever releasing it because the guy that wrote it was lazy, as lazy as me. Now, you want to reuse it in a loop. What do you do? Contrary to some people that will start crying to that &@@""#~ programmer that wrote this sh!!!! you keep your cool and you do the following:
14
3837
by: vivek | last post by:
i have some doubts on dynamic memory allocation and stacks and heaps where is the dynamic memory allocation used? in function calls there are some counters like "i" in the below function. Is this stored in stack. If yes whether it will be deleted on exiting from the function. is dynamic memory allocation needed for this purpose
66
3708
by: karthikbalaguru | last post by:
Hi, Will 'free' return the memory Immediately to the OS ? Thx in advans, Karthik Balaguru
0
9619
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
9454
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
10261
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
8934
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...
1
7460
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
5354
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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
3609
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.