"Learning the path to iOS: C-language" storage memory partitioning

Source: Internet
Author: User

I. partitioning of memory storage areas :

1. Stack area : The stack area mainly stores variables , arrays defined inside the function . function call , open space , function execution complete , reclaim space , space opening and recycling have System management .

2. Heap Area : The largest feature of the heap area : the opening and release of space has developers manually managed .

3. Global zone static zone : The main storage function outside the definition of global variables and static variables , space once opened , will not be recycled . Until the end of application execution .

4. constant Area : Storage Constants . 1. Shaping Constants . 2. Floating-point constant. 3, string constant . 4. String Constants .

5. Code Area : The CPU instructions generated after the program is compiled .

Two. malloc, which opens up space in the heap area.

        Open up space in the heap area.    void * Generics: can represent all pointer types.    If you want to store two integers, use int *, store 8 characters, use char *, store 4 person integers, with short *.    malloc opens an N-byte space in the heap area, returning the first address of the space.    Char *p = malloc (8);    Store iphone    strcpy (P, "iphome");    printf ("%s\n", p);//iphome    //Free space    //Delete just mark Delete, not clear the contents of the space.    Free (p); p = NULL;

Three. Space problems in the heap area.

1. Wild pointer problem : access to space without ownership .

2. over-release : Once a space is released several times , the program crash immediately .

3. memory leak : space is not released, causing memory to accumulate . will not cause immediate crash, Security risks .

Processing method: P = NULL;

Prerequisites for using pointers: 1. the pointer should be directed by a clear point .

2. point to a controllable area


Four. malloc Application

1. An array space with 5 elements . Stores 5 integers .

    int  *p = malloc (sizeof (int.));    for (int i = 0; i < 5; i++) {        P[i] = arc4random ()% (40-20 + 1) +;        printf ("%d", P[i]);    }    printf ("\ n");       Sort for    (int i = 0, i < 5-1; i++) {for        (int j = 0; J < 5-1-I, J + +) {            if (P[j] > p[j + 1]) {                int temp = p[j];                P[J] = p[j + 1];                P[j + 1] = temp;}}    }    for (int i = 0; i < 5; i++) {        printf ("%d", P[i]);    }        Free (p);    p = NULL;


2. There is a string,which contains numbers,Extracting numbers from them,Requires dynamic allocation of memory storage.
    printf ("Please enter a string: \ n");    Char str[] = {0};    scanf ("%s", str);    int i = 0;    int num = 0;    while (str[i]! = ' + ') {        if (str[i] >= ' 0 ' && str[i] <= ' 9 ') {            num++;        }        i++;    }    Char *q = malloc (sizeof (char) * (num+1));//Generate space based on length num + 1 string hidden by    int m = 0,n = 0;    for (int i = 0, i < num; i++) {while        (str[m]! = ') {            if (str[m] >= ' 0 ' && str[m] <= ' 9 ') { C17/>q[n] = str[m];                n++;            }            m++;        }    }    Q[n] = ' + ';//More Out of storage    ("\ n");    for (int i = 0; i < num; i++) {        printf ("%c", Q[i]);    }    Free (q);    Q = NULL;

3. Enter the name of the 3 learners , dynamically allocate memory to save the learner name, and at the end of the output .

       Char *names[3] = {0}; The first address of the space stored in the heap area.    Char temp[255] = {0};//stores the string input from the console for    (int i = 0; i < 3; i++) {        printf ("Please enter the names of 3 students");        scanf ("%s", temp);//input into temp temporary array.        Dynamically computes the length of the input string        unsigned long length = strlen (temp);        Open up space in the heap area.        Names[i] = malloc (length + 1);//stores the address of the heap space in an array of pointers,         //copies the contents to the heap area.        strcpy (Names[i], temp);            }        for (int i = 0; i < 3; i++) {        printf ("%s \ n", Names[i]);        Free (names[i]); <span style= "font-family:arial, Helvetica, Sans-serif;" >//release of Space </span>        names[i] = NULL;         }


(2) Calloc usage

       1.void * CALLOC (unsigned n, unsigned size);    Allocates n sizes of size space. And clear all bytes of that memory by 0.    int *p = Calloc (5, 4);//Allocate 5 block size to 4 bytes of space, and do clear 0 operation.        Free (p);    p = NULL;
(3) ReAlloc usage

     void *realloc (void *p,unsigned newSize);    int *p = malloc (ten);    printf ("%p\n", p);    int *q = ReAlloc (P, 40);//reassign a space of size 100.    ReAlloc returns the first address of the current space. If the current space is not enough, then another chunk is requested for 20 bytes of space, at which point the address of the new space is returned.    printf ("%p\n", q);    Free (q);    Q = NULL;    p = null;//does not need to be released.

(4) memcpy usage

    void *memcpy (void *dest, const void *source, size_t n);      From source, point to memory and start copying to n bytes in dest.          Char *p1 = malloc (8);     Char *p2 = malloc (8);          strcpy (P2, "Frank");     printf ("%s\n", p2);     memcpy (P1, p2, 6);          memcpy (P1, P2, 4);     memcpy (P1, p2 + 2, 4);//ank     p1[4] = ' + ';     printf ("%s\n", p1);//fran
(5) Memset usage

   <pre name= "code" class= "CPP" >4. void * memset (void *s, int c, size_t n);    The memory starting from S points to initialize n bytes of content for C    char *p1 = malloc (8);    memset (p1,0,8);

Five. Practice

Define two integer pointers, save 3 elements with malloc,calloc for their allocated space, andmalloc allocated space with memset zeroed, The random array is assigned a random range 1-3, and the value is compared with memcmp two arrays. If the same print good! Otherwise print Failed.

    int *p = malloc (sizeof (int) * 3);    int *q = calloc (3, sizeof (int));    memset (p, 0, sizeof (int) * 3);    for (int i = 0;i < 3;i++) {        P[i] = arc4random ()% (3-1 + 1) + 1;        Q[i] = arc4random ()% (3-1 + 1) + 1;        printf ("p:%d q:%d\n", P[i],q[i]);    }   Compare whether Buf1 and Buf2 point to the same memory, compare count bytes        if (memcmp (p, q, sizeof (int) * 3) = = 0) {//address. 3 is 3 bytes.            printf ("profect\n");        } else {            printf ("failed\n");        }        Free (p);    Free (q);    p = NULL;    Q = NULL;

Six. Macros

define macros : three parts : 1. #define 2. Macro Name 3. What to replace

The function of a macro : replace only .

Naming conventions for macro names : 1. All CAPS 2. K + Hump

no parameter macro #define Karraynumber5 #define N

#define MUL (a) (a) * (B))

The macro should be aware of several issues .

1. Macro Name Capitalization

2. The parameters must be enclosed in parentheses .

3. do not add a semicolon to the contents of the macro replacement .

4. for a parameter macro , do not add a space between the macro name and the parameter .


Seven. Enumeration

Defining enumerations

The role of enumerations : list out all possibilities

Enumeration is the combination of identifiers that people can recognize and numbers that a computer can recognize .

Example:

Defines an enumeration typedef enum BUTTON {    //by 1 for each bit to represent a state.    Close = 1 << 0,//off 001    first bit 1 means off    Max = 1 << 1,//Maximize 010   The second bit is 1 means maximize    min = 1 << 2//Minimize 1      the third digit of 1 indicates the minimization of    }button;
   If you want to baby more than one enumeration value, bitwise or can, provided that the enumeration value is shifted by the left symbol corresponding to the value.   BOOL B = Close | Max | Min; 001 010 = 111   printf ("%d\n", b);

Eight. Conditional compilation

Start with # is called pre-compilation instructions

Precompiled directives do some textual work and replace the code .

Form 1:

#define A#IFDEF a    int a = 10;//conditional compilation (different code compiled according to the conditions) #else    int A = +; #endif    printf ("%d", A);//10
Form 2:

#define A#IFNDEF A//If you do not define    an int a = 10;//conditional compilation (different code compiled according to the conditions) #else    int a = +; #endif    printf ("%d\n", A);//20

Form 3:

# if  10//Non 0 is true, execute if, otherwise false, execute else    int a = ten, #else    int b =: #endif    printf ("%d\n", a);//10
Nine.Face Test#includewith the#importthe Difference

#import #include prevents duplicate imports , resulting in cross-compilation .

#import "" to import a custom header file

header file for #impoer <> import System


















"Learning the path to iOS: C-language" storage memory partitioning

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.