5 major areas of memory with 3.1 OC features, 5 major oc

Source: Internet
Author: User

5 major areas of memory with 3.1 OC features, 5 major oc

This article is the basic knowledge of Objective-C language. In order to give you a clearer understanding, many code cases and sections have been compiled in this article. If there are any errors, I hope to correct them, we are willing to exchange and learn from each other and make progress together! --- "Flying Monkey _ A Xin" (also pay tribute to Dao Ge)

This article aims to understand the five regions of memory and their respective responsibilities

Directory structure

  • 00. Brief Description
  • 01. Allocation and release (frequently asked during interviews)
  • 02. Stack and stack
    • 2.1 stack Zone
      • 2.1.1 storage in the stack area (Responsibilities/contents of the stack Area)
      • 2.1.2 stack features
      • 2.1.3 others
    • 2.2 heap Zone
      • 2.2.1 save in heap:
      • 2.2.2 ability to express the features of the heap Zone
  • 0.3 global variables, static variables, and constants
    • 3.1 memory region where global variables/static variables/constants are stored
      • 3.1.1 storage area of global and static variables in textbooks
      • 3.1.2 storage area of global and static variables in Xcode 8
      • Note: (Global/static variables, constants) there is a difference between textbook and xcode8 verification.
        • (1) Test the actual storage region of xcode8 "global variables:
        • (2) Test the actual storage region of xcode8 "static variables:
          • So --> interview notes:
        • (3) Test the actual storage region of xcode8 "constant:
    • 3.2 BSS segment (static zone)
    • 3.3 Data Segment (constant zone)
    • 3.4 Differences between global variables and Global static variables
        • Note:
          • 1. Why almost no global variables are used in OC?
          • 2. The global variables cannot be defined in the header file.
          • 3. During program development, both global variables and static variables cannot be renamed.
          • 4. Modifications to static variables are usually made only within the file that defines the current static variables.
    • 3.5 correct usage of static variables
    • 3.6 Constants
  • Review of the main learning objectives of this article:
    • 1.1 name of the five memory areas
    • 1.2 responsibilities and features of memory stack/stack
    • 1.3 memory region for storing global variables/static variables/Constants
  • Conclusion
00. Brief Description

The first step is to load the program into the memory.
Five Major Areas of memory: Stack zone, heap zone, BSS segment (static zone), constant zone (Data Segment), and code segment.

01. Allocation and release (frequently asked during interviews)
  • Stack Zone(Stack [st Release k]): automatically assigned and released by the compiler

  • Heap Area(Heap [hi, p]): allocated and released by programmers. If the programmer does not release, memory leakage may occur.

  • BSS segment: The program is released by the system after the program ends.

  • Data Segment: The program is released by the system after the program ends.

  • Code segment: The program is released by the system after the program ends.

    Binary executable code after the program compilation Link

02. Stack and stack
Int main (int argc, const char * argv []) {// local variables are stored in the stack zone. // After the stack zone variables are out of scope, NSInteger I = 10; NSLog (@ "% zd", I) will be destroyed; // The local variable is saved to the right of the // value assignment statement in the stack, the object created using the new method is saved in the heap zone's // xinge variable, recording the address of the heap zone // There is a memory management mechanism in the OC, it is called 'arc' and can automatically manage the lifecycle of the object created by the OC code. // Therefore, when developing the OC program, programmers usually do not need to consider the memory release work LJXPerson * xinge = [LJXPerson new]; NSLog (@ "% @", xinge); return 0 ;}

10
<LJXPerson: 0x100404b70>

2.1 stack Zone

Stack [st Release k]: automatically allocated and released by the compiler

2.1.1 storage in the stack area (Responsibilities/contents of the stack Area)
  • Local variable
  • Method Parameters(Eg: in the main function, call methods and real parameters in methods)
2.1.2 stack features
  • Limited storage spaceThe iphone stack size is only512k(Default), very limited
  • ContinuityThe stack address is continuous.
Some code: # import <Foundation/Foundation. h> # import "LJXPerson. h "int main (int argc, const char * argv []) {@ autoreleasepool {NSInteger I = 10; NSLog (@" I stack address is % p ", & I); NSInteger j = 10; NSLog (@ "the stack address of j is % p", & j); // In the xiaoming variable, stores the memory address of the LJXPerson object (heap memory address) LJXPerson * xinge = [LJXPerson new]; NSLog (@ "xinge stack address is % p ", & xinge); double height = 10; NSLog (@ "the stack address of height is % p", & height );.......

The stack address of I is 0x7fff5fbff768.
The stack address of j is 0x7fff5fbff760.
The stack address of xinge is 0x7fff5fbff758.
The stack address of height is 0x7fff5fbff750.

  • Address allocation from large to smallStack zone addresses are arranged in the order of allocation from large to small
  • Fast Access.
  • System Management. (The stack memory is managed by the system)
2.1.3 others
If you call a method in a program, a "stack frame" is enabled ". (This stack frame can be understood as a continuous area) the address of the stack frame and the address of the previous local variable are not the real parameter addresses recorded in the consecutive stack frame, and after the local variable method in the method is executed, the stack frame is destroyed (the stack is shot) <this way, after each execution is completed, the stack is released to release the memory, this will always ensure that the memory occupied by the stack area is not very large> so-out-of-class talk-> during development, if every method is short, at the same time, each method declares few variables. this will definitely save the memory.


See Figure Zhiyi

Add "in a function/method"

That is, up to 65536 can be defined in a function/method. ---> because the stack releases memory after "every time" One method is executed"

Concept of Stack: backward, forward, and backward

See the figure below:

NSLog (@ "number of bytes occupied by the NSInteger variable % tu", sizeof (NSInteger); NSLog (@ "number of bytes occupied by the double variable % tu", sizeof (double )); NSLog (@ "the number of bytes occupied by the xinge variable % tu", sizeof (xinge); // prompt: in the stack area, only suitable for storing very small data NSLog (@ "on iPhone, up to % zd local variables can be defined in a function/method", 512*1024/8 ); // storage of real parameters in the stack area during the call of the test method [xinge sumWithNum1: I andNum2: j];

Summary: How the stack zone works when calling a Method * Enable stack frame * save real parameters * save local variables * after the method is complete, the stack is played, the stack frame is destroyed, and space is released.
2.2 heap Zone

Heap [hi! p]: allocated and released by programmers. If not released, memory leakage may occur.

2.2.1 save in heap:
  • Objects created using the new method are saved in the heap area.
  • All member variables of the created object are stored in the heap.
The responsibility of the heap area is to "solve the problem of limited stack space" * OC uses the 'new' method to create objects ---> {due to ** ARC Management Mechanism **, OC programmers usually do not need to consider the release of objects .} (In OC, there is a memory management mechanism called ARC (automatic reference count) which can automatically manage the lifecycle of the object created by the OC code) * The space allocated by using the malloc, calloc, and realloc functions in C must be released using the free function.

Gu: when developing OC programs, programmers usually do not need to consider memory release.
However, if the OC Code uses a function that allocates space in the C language, you need to consider releasing the memory.

1. the size of the heap is determined by the system, including the system memory/disk swap space... 2. the system uses the 'linked list' to manage the memory allocation in the heap area. 3. {** the programmer only needs to allocate and release the memory in the heap zone **}
2.2.2 display the features of the heap zone. 0.3 global variables, static variables, and constants. 3.1 global variables, static variables, and constants.

Developers must keep changes within a limited scope.

3.1.1 storage area of global variables and static variables in textbooks 3.1.2 storage area of global variables and static variables in Xcode 8 Note: (Global/static variables, constants) there is a difference between textbooks and xcode8 verification. (1) Test the actual storage region of xcode8 "global variables:

Case code:

# Import <Foundation/Foundation. h> NSInteger num1 = 10; // defines the first global variable and initializes NSInteger num2; // defines the second global variable and does not initialize int main (int argc, const char * argv []) {@ autoreleasepool {// note: In Xcode 8, global variables are initialized or not, NSLog (@ "1st addresses of global variables % p", & num1 ); // address of 1st Global variables: 0x100001188 NSLog (@ "Address of 2nd global variables: % p", & num2 ); // address 0 x 2nd num2 = 100001190 for 100 global variables; NSLog (@ "Address of 2nd global variables % p (after initialization)", & num2 ); // address of 2nd global variables: 0x100001190 (after initialization)} return 0 ;}


Addresses of 1st Global variables: 0x100001188
Addresses of 2nd global variables: 0x100001190
Address 0 x 2nd of the 100001190 global variables (initialized)
Program ended with exit code: 0

Visible 1: The address is continuous from small to large.

Visible 2:

In Xcode 8, the address remains unchanged regardless of whether the global variable is initialized or not.

(2) Test the actual storage region of xcode8 "static variables:
# Import <Foundation/Foundation. h> static NSInteger num1 = 10; // defines the first global variable and initializes static NSInteger num2; // defines the second global variable and does not initialize static NSInteger sNum1 = 10; // define the first static global variable and initialize static NSInteger sNum2; // define the second static global variable without initializing int main (int argc, const char * argv []) {@ autoreleasepool {// note: In Xcode 8, the address remains unchanged, regardless of whether the global variable is initialized or not (@ "1st Global variable address % p", & num1 ); // address of 1st Global variables 0x000011f8 NSLog (@ "Address of 2nd global variables % p", & num2 ); // address 0 x 2nd num2 = 100001208 for 100 global variables; NSLog (@ "Address of 2nd global variables % p (after initialization)", & num2 ); // address of 2nd global variables: 0x100001208 (initialized) NSLog (@"#################################### ##########"); NSLog (@ "1st static global variable address % p", & sNum1 ); // address of 1st static global variables: 0x100001200 NSLog (@ "Address of 2nd static global variables: % p", & sNum2 ); // address of 2nd static global variables: 0x100001210 sNum2 = 100; NSLog (@ "Address of 2nd static global variables: % p (initialized )", & sNum2); // the address of the 2nd static global variables 0x100001210 (after initialization)} return 0 ;}

Address 0x000011f8 of the 1st Global Variables
Addresses of 2nd global variables: 0x100001208
Address 0 x 2nd of the 100001208 global variables (initialized)
################################
1st static global variable addresses 0x100001200
2nd static global variable addresses 0x100001210
2nd static global variable addresses 0x100001210 (initialized)
Program ended with exit code: 0

1. The address of the static variable before and after initialization remains unchanged.

2. Static variables and global variables are saved at the same time.

So --> interview notes:
----> In xcode 8, static variables and global variables are stored in the same region ----> In xcode 8, both static variables and global variables are saved in the BSS segment. there is a difference from our teaching books. so --> when we encounter this problem during the interview, we can answer the following question: the BSS segment stores uninitialized global and static variables. However, after xcode8 verification, both global and static variables are stored in the BSS segment.
(3) Test the actual storage region of xcode8 "constant:
# Import <Foundation/Foundation. h> NSInteger num1 = 10; NSInteger num2; static NSInteger sNum1 = 10; static NSInteger sNum2; const NSInteger cNum = 10000; // defines a constant int main (int argc, const char * argv []) {@ autoreleasepool {NSLog (@ "1st addresses of global variables % p", & num1 ); NSLog (@ "2nd addresses of global variables % p", & num2); num2 = 100; NSLog (@ "Address of 2nd global variables % p (after initialization) ", & num2 ); NSLog (@"#################################### ##########"); NSLog (@ "1st static global variable address % p", & sNum1); NSLog (@ "2nd static global variable address % p", & sNum2 ); sNum2 = 100; NSLog (@ "2nd static global variable address % p (initialized)", & sNum2 ); // address of 2nd static global variables: 0x100001230 (initialized) NSLog (@"#################################### ##########"); NSLog (@ "Address of 1st constants % p", & cNum); // address of 1st constants 0x100000e88} return 0 ;}

Addresses of 1st Global variables: 0x100001218
Addresses of 2nd global variables: 0x100001228
Address 0 x 2nd of the 100001228 global variables (initialized)
#################
1st static global variable addresses 0x100001220
2nd static global variable addresses 0x100001230
2nd static global variable addresses 0x100001230 (initialized)
##################
Address 0x100000e88 of 1st Constants
Program ended with exit code: 0

Constant storage Demo:In case of an interview, you can explain the difference between the two.

Visible: global variables and static variables are placed in different regions from constants, and constants are stored in the constant area (or data segment ). * textbook: data segments (constant areas) are used to store initialized global variables, static variables, and constants. * xcode8: a constant is stored in the data segment (constant area.
3.2 BSS segment (static zone)

Stored content: (verified in previous cases ):
1.Textbooks: StorageNot initializedGlobal and static variables
2.Xcode 8 Verification: Whether initialization or notBoth global and static variables are stored..

3.3 Data Segment (constant zone)

Stored content: (verified in previous cases ):

3.4 Differences between global variables and Global static variables
  • Note:
Note: 1. Why almost no global variables are used in OC?
1. because the global variables can be modified at any position of the program. 2. once the program encounters an error caused by a global variable, it is difficult to troubleshoot the error 3. using global variables is not a good habit. [my understanding: when we develop many files, we cannot define global variables in header files (if they are defined in header files, when another class introduces this header file, it is equivalent to defining the global variable in both classes, and there will be repeated definitions), almost none of them are used.]
2. The global variables cannot be defined in the header file.

(My understanding: If it is defined in the header file, when another class introduces this header file, it is equivalent to defining this global variable in both classes and there will be repeated definitions)

3. During program development, both global variables and static variables cannot be renamed.

(My understanding: When the name is the same as another variable, it will be modified by the variable with the same name .)

4. Modifications to static variables are usually made only within the file that defines the current static variables.

Even if the external address is modified, it does not affect the external address.Defining static variable filesInternal numeric changes
Once an error occurs due to a static variable in the program, you only need to check the code for modifying the static variable in the current file. The difficulty of troubleshooting the error is relatively reduced.

Tip: During program development, if you want to use a global variable, you should define a global static variable in. m instead of exposing the variable to the header file.--> The smaller the variable range, the more controllable it is.

------------------ LJXPerson. h --------------------- # import <Foundation/Foundation. h> // static NSInteger num1 = 99; // defines a Global static variable @ interface LJXPerson: NSObject/** test Method */-(void) test; @ end ---------------- LJXPerson. m --------------------- ** LJXPerson. m ** # import "LJXPerson. h "@ implementation LJXPerson-(void) test {num1 --; NSLog (@" % p % zd ", & num1, num1) ;}@ end ---------------- main. m ------------------------- # import <Foundation/Foundation. h> # import "LJXPerson. h "int main (int argc, const char * argv []) {// test the Global static variable NSLog (@" Address of the Global static variable defined in LJXPerson % p, % zd ", & num1, num1); num1 = 777777; NSLog (@" Address of the Global static variable defined in LJXPerson % p, % zd ", & num1, num1); LJXPerson * xinge = [LJXPerson new]; [xinge test]; LJXPerson * xiaoming = [LJXPerson new]; [xiaoming test]; NSLog (@ "Address of the Global static variable defined in LJXPerson % p, % zd", & num1, num1); return 0 ;}

The address of the Global static variable defined in LJXPerson is 0x1190,99.
The addresses of Global static variables defined in LJXPerson are 0x1190,777777.
0x100001198 98
0x100001198 97
The addresses of Global static variables defined in LJXPerson are 0x1190,777777.

Pass: The above output results have also been verified for the above description. Lines 6, 7, 8, 13, and 14 of the following code are external calls, that is, the value of the variable corresponding to the address 0x00001190 is modified. Only when the object calls the method is the internal static variable called.

// Test the Global static variable 6. NSLog (@ "Address of the Global static variable defined in LJXPerson % p, % zd", & num1, num1); 7. num1 = 777777; 8. NSLog (@ "Address of the Global static variable defined in LJXPerson % p, % zd", & num1, num1); 9. LJXPerson * xinge = [LJXPerson new]; 10. [xinge test]; 11. LJXPerson * xiaoming = [LJXPerson new]; 12. [xiaoming test]; 13. NSLog (@ "Address of the Global static variable defined in LJXPerson % p, % zd", & num1, num1); 14. return 0 ;}

In the main function: comment out the following code

// NSLog (@ "Address of the Global static variable defined in LJXPerson % p, % zd", & num1, num1); // num1 = 777777;


The address of the Global static variable defined in LJXPerson is 0x1190,99.
0x100001198 98
0x100001198 97
The address of the Global static variable defined in LJXPerson is 0x1190,99.

3.5 correct usage of static variables

That is, the role of the static keyword

------------------ Declaration --------------------- # import <Foundation/Foundation. h> @ interface LJXPerson: NSObject/** test Method */-(void) test; @ end ------------------- implement -------------------- # import "LJXPerson. h "@ implementation LJXPerson-(void) test {static NSInteger num1 = 99; // defines the local static variable num1 --; NSLog (@" % p % zd ", & num1, num1);} @ end ------------------- main program -------------------- # import <Foundation/Foundation. h> # import "LJXPerson. h "int main (int argc, const char * argv []) {LJXPerson * xinge = [LJXPerson new]; [xinge test]; LJXPerson * xiaoming = [LJXPerson new]; [xiaoming test]; return 0 ;}

2030-03-31 15:12:48.504 demo[5399:535229] 0x100001170 98
2030-03-31 15:12:48.505 demo[5399:535229] 0x100001170 97
Program ended with exit code: 0

3. If the current class file containsMultiple methodsUse the static variable, and then modify the static variable to the global

------------------ Declaration --------------------- # import <Foundation/Foundation. h> @ interface LJXPerson: NSObject/** test Method */-(void) test;-(void) demo; @ end ------------------- implement ------------------ # import "LJXPerson. h "// In the current class file, there are multiple methods used to use this static variable and put it in the Global static NSInteger num1 = 99; @ implementation LJXPerson-(void) test {num1 --; NSLog (@ "% p % zd", & num1, num1) ;}- (void) demo {num1 ++; NSLog (@ "% p % zd", & num1, num1) ;}@ end ------------------- main program -------------------- # import <Foundation/Foundation. h> # import "LJXPerson. h "int main (int argc, const char * argv []) {LJXPerson * xinge = [LJXPerson new]; [xinge test]; [xinge demo]; LJXPerson * xiaoming = [LJXPerson new]; [xiaoming test]; [xiaoming demo]; return 0 ;}

0x1000011b0 98
0x1000011b0 99
0x1000011b0 98
0x1000011b0 99

3.6 Constants

Purpose: defineFixedValue, which is used globally. For example, the company website address, telephone number, etc.

The function of extern: extern keyword, which indicates the value of the constant. It is set in other files and can be used externally.

Note: In a project, a constant cannot be named again. Therefore, when defining a constant, it should be as long as possible with a prefix to ensure that duplicate names will not occur.

Review of the main learning objectives of this article:

Five areas of memory

The program must be loaded to the memory before execution.

1.1 name of the five memory areas

Name of the five regions in the memory
Stack Zone
Heap Area
BSS segment (static zone)
Data Segment (constant zone)
Code segment

1.2 responsibilities and features of memory stack/stack

Ability to express stack responsibility (storage content)

  • Local variable
  • Method Parameters

Ability to express stack features
512 K
Continuous
From big to small
Fast
System Management
Ability to describe how the stack works when calling a method
Enable stack frame
Save real parameters
Save local variables
After the method is completed, the stack is shot, stack frames are destroyed, and space is released.
Ability to express the responsibilities of the heap area (storage content)

  • Because of the ARC Management Mechanism, OC programmers usually do not need to consider the release of objects.
  • Use the free function to release the space allocated by using the malloc function in C.

Ability to express the features of the heap Zone
All programs share
Store Big Data
Programmer Management
Discontinuous
Speed without stack speed

1.3 memory region for storing global variables/static variables/Constants

Developers must keep changes within a limited scope.

Ability to express the storage area of global and static variables in textbooks

  • Global variables and static variables with initial values are stored in the data segment (constant area)
  • Global variables and static variables without an initial value are stored in the BSS segment (static zone). When an initial value is set for a global or static variable, they are moved to the Data Segment (constant zone)

Region where global variables and static variables in Xcode 8 are stored

  • Whether or not to set the initial value, global variables and static variables are saved in the BSS segment (static zone)Specifies the storage area of constants.Constants are stored in the data segment (constant area)Can tell why almost no global variables are usedDevelopment requires that changes be controlled within a limited range and global variables cannot be defined in the header file. Otherwise, repeated definitions may occur #1.4 memory static variables/constants usage

Ability to express the role of the static keyword

Ability to correctly use static variables
* If only one method is used, the static variables are defined inside the method.
* If multiple methods are used, define static variables in. m.
* Do not define static variables in header files.

Ability to express the functions of constants

Define a fixed value and use it globally, such as the company's website or phone number...
In iOS development, constants are usually used only when the notification string is defined.

Can tell the correct usage of constants

Define constants in. m and set the Initial Value
Const NSInteger cNum = 99;
Use the extern keyword in. h to declare that a constant is defined in another position and has been assigned a value. You can use it externally.
Extern const NSInteger cNum;
Constant names should be as long as possible to avoid duplicate names

Conclusion

OK! Does the above basic knowledge about the five regions of memory play a learning role for you? If there is any error, please correct it! Thank you! Make common progress in related learning! I sincerely hope that one of the knowledge points can help you!







The above content directory structure(Click to change)

  • 00. Brief Description
  • 01. Allocation and release (frequently asked during interviews)
  • 02. Stack and stack
    • 2.1 stack Zone
      • 2.1.1 storage in the stack area (Responsibilities/contents of the stack Area)
      • 2.1.2 stack features
      • 2.1.3 others
    • 2.2 heap Zone
      • 2.2.1 save in heap:
      • 2.2.2 ability to express the features of the heap Zone
  • 0.3 global variables, static variables, and constants
    • 3.1 memory region where global variables/static variables/constants are stored
      • 3.1.1 storage area of global and static variables in textbooks
      • 3.1.2 storage area of global and static variables in Xcode 8
      • Note: (Global/static variables, constants) there is a difference between textbook and xcode8 verification.
        • (1) Test the actual storage region of xcode8 "global variables:
        • (2) Test the actual storage region of xcode8 "static variables:
          • So --> interview notes:
        • (3) Test the actual storage region of xcode8 "constant:
    • 3.2 BSS segment (static zone)
    • 3.3 Data Segment (constant zone)
    • 3.4 Differences between global variables and Global static variables
        • Note:
          • 1. Why almost no global variables are used in OC?
          • 2. The global variables cannot be defined in the header file.
          • 3. During program development, both global variables and static variables cannot be renamed.
          • 4. Modifications to static variables are usually made only within the file that defines the current static variables.
    • 3.5 correct usage of static variables
    • 3.6 Constants
  • Review of the main learning objectives of this article:
    • 1.1 name of the five memory areas
    • 1.2 responsibilities and features of memory stack/stack
    • 1.3 memory region for storing global variables/static variables/Constants
  • Conclusion

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.