473,387 Members | 3,821 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

allocation of memory

hello,
will someone please explain me when and where is memory allocated for static variables which are declared inside a function and static variable declared outside of all functions(global) and also for global variables which are not static?
Jul 17 '10 #1
16 2336
Banfa
9,065 Expert Mod 8TB
All those types of variables have data reserved and initialised for them in the programs data segment by the c start-up code which runs after the program has started and before main is entered.
Jul 17 '10 #2
@Banfa
please explain me a little more i cannot not understand
Jul 17 '10 #3
donbock
2,426 Expert 2GB
A common problem is for different people to use different terms for the same concept; or worse, the same term for different concepts. Perhaps you should tell us a little of what you understand about memory allocation. Then we can be careful to phrase the responses more carefully.

Also, it would help to understand why you are asking this question. You may have a larger issue that we could address directly.

banfa: too bad I don't have any work done on your suggestion yet. ;-)
Jul 17 '10 #4
@donbock
sir,
please look at the following snippet
Expand|Select|Wrap|Line Numbers
  1.        #include<stdio.h>
  2.        #include<conio.h>
  3.       static int a;   //static variable declared globally
  4.        main()
  5.        {
  6.        int fun();
  7.        clrscr();
  8.        fun();
  9.        getch();
  10.         }
  11.         int  fun()
  12.         {
  13.         static int b;//static variable declared locally
  14.         printf("hai");
  15.         }             
  16.  
my question is when is memory allocated for variables a and b?they say that memory static variables get created in data segment which cannot be extented later in the run time of program.since static variable b is created inside function i assumed that variable b will be allocated memory only when it enters the function.
but later knowing about the data segment and its inability to extend the size i came to the conclusion that i am wrong.is my conclusion a correct one?if so will static get created in stack or will some other mechanism take place?please explain.
Jul 17 '10 #5
weaknessforcats
9,208 Expert Mod 8TB
All variables (static or not) defined outside a function are allocated before main() starts.

All variables (static or not) defined inside a function are allocated when the function is called. The single variation is the static variable defined inside a function. In this case, the compiler generates code to allocate the variable when the function is first called. For all subsequent calls, the variable is not re-allocated but instead the variable allocated by the first call is used.

These static variables and any global variables (static or not) are kept in an area of memory that remains allocated for the duration of the program.

BTW: A static global variable is no different from a regular (extern) global variable. Here the "static" refers to the linkage. Static global variables can referred to only in the file where they are defined whereas the extern global variables can be referred to from any file in the program.
Jul 17 '10 #6
@weaknessforcats
"A data segment is one of the sections of a program in an object file or in memory, which contains the global variables and static variables that are initialized by the programmer. It has a fixed size, since all of the data in this section is set by the programmer before the program is loaded. However, it is not read-only, since the values of the variables can be altered at runtime. "
i got it from
http;//enwikipedia.org/wiki/data_segment
this is where my doubt starts.i agree that static variable gets created inmemory only once .but if it gets created only when function is called.by that time data segment cannot expand.so what happens?please explain this is my doubt
Jul 18 '10 #7
@donbock
"A data segment is one of the sections of a program in an object file or in memory, which contains the global variables and static variables that are initialized by the programmer. It has a fixed size, since all of the data in this section is set by the programmer before the program is loaded. However, it is not read-only, since the values of the variables can be altered at runtime. "
i got it from
http;//enwikipedia.org/wiki/data_segment
this is where my doubt starts.i agree that static variable gets created inmemory only once .but if it gets created only when function is called.by that time data segment cannot expand.so what happens?please explain this is my doubt
Jul 18 '10 #8
donbock
2,426 Expert 2GB
I agree with weaknessforcats that all variables defined outside a function are allocated [and initialized] before main() starts. I disagree with him that all static variables defined within a function are allocated (and initialized) when the function is first called. I suggest that it is permissible, but necessarily true, for the static variables defined within a function to also be allocated (and initialized) before main() is called. Notice that there is no perceptible difference between these two possibilities. "A difference that makes no difference is no difference."

Quoting the definition of "data segment" illustrates my concern with your recent "doubt" posts. You ask general questions about implementation-dependent issues. A response that is restricted to what the Standard says is incomplete -- it doesn't really answer your question. A complete response is inaccurate -- it is only true for some subset of compiler implementations.

The C Standard doesn't mention data segments. It is true that data segments are a tool used by most, if not all, compilers. However, each compiler is free to define the specific attributes of this tool in whatever way seems most useful to the developers of that compiler. The definition you cite is typically true as far as it goes, but in the absence of any Standard on data segments a compiler vendor is not going to get in trouble with anybody if their implementation is able to dynamically resize a data segment while the program is running.
Jul 18 '10 #9
weaknessforcats
9,208 Expert Mod 8TB
I disagree with him that all static variables defined within a function are allocated (and initialized) when the function is first called.

Consider a program with 5000 functions that have static variables but you call none of these functions. It's not reasonable that 5000 static variables will be created and initialized before main starts. Especially in C++ where you may need to call a constructor that has arguments for the amount of memory needed.
Jul 18 '10 #10
Banfa
9,065 Expert Mod 8TB
Well I have to say I was all set to wade into this in support of Dons point of view, but I decided a little testing was in order first.

Initially I tried testing putting a large static array of int inside a function and seeing if it need to be called to be created by checking the memory allocated to the program in the system monitor. Unfortunately the results where indeterminate, that is the amount of memory allocated to the program never really changed for a reason I have not determined.

However I then realised that if I allow myself to use C++ then I can easily test using a simple class with output from the constructor (of course I am not sure how valid it is to output before main has been entered but it appeared to work.

So here is my test program

Expand|Select|Wrap|Line Numbers
  1. #include <string>
  2. #include <iostream>
  3.  
  4. class Tester
  5. {
  6. public:
  7.     Tester(const char *name)
  8.     : me(name)
  9.     {
  10.         std::cout << "Constructing: " << me << std::endl;
  11.     }
  12.  
  13.     ~Tester()
  14.     {
  15.         std::cout << "Destructing: " << me << std::endl;
  16.     }
  17.  
  18. private:
  19.     std::string me;
  20. };
  21.  
  22. static Tester tg("global");
  23.  
  24.  
  25. void function()
  26. {
  27.     std::cout << "Enter function" << std::endl;
  28.     static Tester tf("function");
  29.     std::cout << "Exit function" << std::endl;
  30. }
  31.  
  32. int main()
  33. {
  34.     std::cout << "Enter Main" << std::endl;
  35.  
  36.     function();
  37.     function();
  38.  
  39.     std::cout << "Exit Main" << std::endl;
  40.  
  41.     return 0;
  42. }
  43.  
Nothng exceptional and here is the output

Expand|Select|Wrap|Line Numbers
  1. Constructing: global
  2. Enter Main
  3. Enter function
  4. Constructing: function
  5. Exit function
  6. Enter function
  7. Exit function
  8. Exit Main
  9. Destructing: function
  10. Destructing: global
  11.  
Clearly showing that the static variable inside function is constructed the first time it its line of code is executed in function.

So although my gut feeling was that weaknessforcats was wrong and that function scope static data is constructed at c start-up it turns out that I, and my gut, are wrong and weaknessforcats is right (something they have an irritating habit of being).

While I feel that there is room for checking what it says in the standard concerning this it is clear that for my platform(32bit Ubuntu/gcc) at the very least posts #6 and #10 accurately describe what is happening.
Jul 18 '10 #11
Banfa
9,065 Expert Mod 8TB
Actually what I just said in post #11 has an implication for program efficiency. Because a function with static data in it has to branch round the code creating the data every time the function is called except the first time.

Where as the same function but with the data declared statically outside the function does not need to do this branch. It is conceivable for a function either with a large number of static variables or that is called extremely frequently that this hidden branch could cause undesirable inefficiencies.
Jul 18 '10 #12
donbock
2,426 Expert 2GB
I don't use C++, so I'm not competent to say anything about the details of how a C++ compiler allocates memory for variables.

I'm a C programmer. Most of my experience is with cross-compilers for embedded microprocessors that lack operating systems. I'm quite positive (although certainty is not the proof of certitude) that these compilers simply allocate space in text or bss for function-scope static variables. That doesn't mean that other compilers don't work the way weaknessforcats described.

This just emphasizes my earlier point that questions about implementation-dependent features either have lots of correct answers or have no correct answer at all.

This scheme described by weaknessforcats and banfa reminds me of optimistic malloc in Linux, where memory isn't allocated until you try to use it. Once an optimistic memory manager is implemented, it isn't much of a stretch to extend it to handling static variables too. In that case you don't need conditional logic in the function, memory allocation is handled by the MMU exception handler. Banfa mentioned Ubuntu ... I wonder if weaknessforcats might have been describing a linux compiler too.
Jul 19 '10 #13
weaknessforcats
9,208 Expert Mod 8TB
I wonder if weaknessforcats might have been describing a linux compiler too.
I have never heard of optimistic malloc. Basically, I am a C++ guy. In C++ memory is allocated using malloc(). I know about the new operator but actualy the new operator just calls malloc to get the memory and then calls the class default constructor, if necessary.

The thing with static in C++ is that you may need to call a funciton to create your static variable and it may be that the variable cannot be constructed until a file is read. Like this:

Expand|Select|Wrap|Line Numbers
  1. int* getValue()
  2. {
  3.      //assume code to read a parameter file
  4.     int * temp = new int[10]; //assume we read a 10 from  the parameter file
  5.     return temp;   
  6. }
  7.  
  8. void function()
  9. {
  10.      static const int* var = getValue();
  11. }
  12.  
  13. int main()
  14. {
  15.     function();
  16. }
Here the function() has a const static array that it cannot initialize until getValue() is called to get the size of the array. Therefore, var cannot be allocated before the first call to function() because it is a const value and const values must be initialized when they are created. Further, getValue() can't be called until after main() has started.

The call to getValue() will occur only on the first call to function().
Jul 20 '10 #14
donbock
2,426 Expert 2GB
"Optimistic malloc" refers to the memory allocation model in Linux. On linux, malloc never fails! It always returns a non-null pointer. However, the returned pointer points to nonexistent virtual memory. An MMU exception occurs when you dereference the pointer, the exception handler then truly allocates the necessary memory, and your program proceeds none the wiser. However, if there is no memory available, the notorious OOM Killer kills a task and recovers its memory. Typically, but not always, the task killed is the one whose deferred allocation failed.

This is a very brief overview of the linux memory allocation model. I left out lots of details and corner cases.

I'm not aware of any other platform that uses optimistic memory allocation.

My point was that perhaps the native linux compiler uses this same mechanism for static variables; and that might be why you see static variables popping into existence the first time their enclosing function is called. The only change needed to support this is for the MMU exception handler to also initialize the variable after truly allocating it. If so, then this would be linux-only behavior.
Jul 20 '10 #15
donbock
2,426 Expert 2GB
jeyshree: please tell us if you are asking about C or C++.
Jul 20 '10 #16
weaknessforcats
9,208 Expert Mod 8TB
I know Windows doesn't use optimistic malloc.

Thank you for the thumbnail sketch of the process. Very interesting.
Jul 21 '10 #17

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

Similar topics

11
by: stp | last post by:
Hello, I declare the following types: typedef pair<long, string> CEventPair; typedef deque<CEventPair*> EventPairCont;
0
by: Yohan | last post by:
I've create a "VC++ dotnet project" in Visual 2003. When I try to allocate much of memory, i've an exception : "System::Runtime::InteropServices::SEHException" With "VC++ project" none...
6
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...
3
by: Richard | last post by:
I need to dynamically allocation memory at run time for the number of student's records and their test scores for the program code below. I don't understand what the 3 errors i got. I can anyone...
62
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();...
4
by: Tomassus | last post by:
Hi there, I have a problem with dynamic memory allocation. I know that it would have been easier to use vectors methods, but i want to know what i do here wrong. This is one of my methods in...
24
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...
1
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...
4
by: thomas | last post by:
Hello suppose I have simple class like this : /*++++++++++++++++++++++++++++++++*/ #include <cstdlib> #include <iostream> #include <fstream> #include <string> using namespace std; class...
66
by: karthikbalaguru | last post by:
Hi, Will 'free' return the memory Immediately to the OS ? Thx in advans, Karthik Balaguru
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
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,...
0
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...
0
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,...
0
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...

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.