C Language Foundation for iOS development Lesson-10 Dynamic memory Management lesson notes and test exercises

Source: Internet
Author: User

function declaration

int max (int a, int b);

char * getString ();

int main (int argc, const char * argv[]) {

Lesson 10 Dynamic memory management class notes and exercises

Review what you learned last week

The difference between a constant and a variable:

The contents of a constant cannot be modified, only accessible;

Data stored in the variable can be modified at any time.

//

The role of the Const keyword: the modifier variable cannot be changed. Use as Constants

const int a = 10;

The following variables who can not change

Formula: See the const modification who, who will be immutable, the data type int is removed (const followed by the variable, * is one)

int B = 30;

const int *P1 = &b; *P1 immutable; P1 pointer variable, *P1 pointer variable points to the storage space. The const modifier *P1, cannot modify the data on the storage space pointed to by the pointer variable *p1, but P1 can be re-assigned.

//

int *const P2 = &b;//p2 immutable, the data stored in the const adornment P2,P2 cannot be changed, but can be modified by pointer variable P2 (using *P2) to modify the data on the spatial point.

//

int const *P3 = &b;//*p3 immutable, same as P1

//

const int *const P4 = &b;//p4,*p4 not mutable

The contents of variables defined by different data types are stored:

int, short, long: stores integers, integer data.

Float, double: stores decimal, floating-point data.

Char: Character type data.

char *, int *, short *: Storage address

struct student: storing struct member information

struct Student *: Address of the storage structure variable

Array of pointers

Data stored on a constant area cannot be changed.

Char *str1 = "IPhone"; STR1 Store constant string The first address of the IPhone;

//

Char *str2 = "Rose";

Char *STR3 = "Tom";

Char *STR4 = "Jack";

Char *STR5 = "Android";

//

Swap pointer variable

char *temp = str2;

STR2 = STR3;

STR3 = temp;

printf ("%s \ n", STR3);

//

//

Char *strings[5] = {"IPhone", "Rose", "Tom", "Jack", "Android"};

Strings[0] = = str1

//

//

Char *TP = strings[1];

STRINGS[1] = strings[2];

STRINGS[2] = TP;

//

printf ("%s \ n", strings[2]);

//

printf ("%p,%p", STR1, Strings[0]); The same string, which is an address

* The role of

int c = 10;

int *p = &c; When you define a pointer variable, the function of the * is to tell the compiler that the following variable is a pointer variable to store the address.

//

*p = 30; At this point, the function of * is to find the point of storage according to the pointer variable and store the data 30

//

printf ("%d \ n", *p);//Ibid.

//

Dynamic memory

5 Partitions in memory

1. Stack area: The main storage of local variables or arrays, defined within the function, when the function calls to open up space, when the function is over after the recovery of space, memory system for allocation and recycling.

2. Heap Area: Heap area memory manually opened by developers, manually released.

3. Global, Static zone: Storage of global variables, as well as static variables; When the program runs, the space is opened and the program runs to the end of space recycling. Managed by the system.

4. Constant area: Storing constants, integral type, floating point type, character type, string type, the content of constant area can not be modified, read-only

5. Code area: The CPU instructions formed after compiling the program to tell the computer program how to run.

//////

int a = ten, B = 20;

//

printf ("%d\n", Max (A, b));

//

printf ("%s", getString ());

//

////////

How to store data on a heap space.

How to open up space in the heap area

malloc opens a space of n bytes in the heap area and returns the first address of the space. Returns a value type void * Generic, which represents the type of arbitrary pointer.

If you request 8 bytes of space, you receive a variable with different pointer type variables, and the stored data size is different.

char *: 8 character (s)

int *: 2 integers

Short *: 4 integers

Long *: 1 integers

Char *p = malloc (7); Open Space Manually

//

strcpy (P, "IPhone");

printf ("%s\n", p);

//

strcpy (P, "Apple");

printf ("%c\n", * (P + 3));

//

Free (p); Free space manually, the release requires a given start address; release just return the space to the system, which is marked Delete, unclear content.

printf ("%p\n", p); Although the space was freed, the P-saved address was not emptied

printf ("%s\n", p);

//

p = null;//Clears the address in the pointer variable, pointing to an invalid space

//

Common problems with heap area space:

/*

1. Wild pointer error: Access to a piece of space without permission, without access to space. There is a security risk; solution: When the space is returned to the system, empty the address stored in the pointer variable: assign NULL

2. Over-release: free multiple times for a piece of space, and excessive release will immediately lead to crash.

3. Memory leak: Space is not released in time, resulting in memory accumulation. There is no free; Security risks.

*/

Open space stores 5 integers, assigning a value of 10-20

int *a = (int*) malloc (sizeof (int) * 5);

//

for (int i = 0; i < 5; i++) {

* (A + i) = Arc4random ()% (20-10 + 1) + 10;

printf ("%d", * (A + i));

//    }

//

for (int i = 0; i < 5-1; i++) {

for (int j = 0; J < 5-1-I; j + +) {

if (* (A + J) < * (A + j + 1)) {

int temp =* (A + j);

* (A + j) = * (A + j + 1);

* (A + j + 1) = temp;

//            }

//        }

//    }

printf ("\ n");

for (int i = 0; i < 5; i++) {

printf ("%d", * (A + i));

//    }

//

Free (a);

A = NULL;

There is a string that contains a number that extracts a number from it. Requires dynamic allocation of memory storage

Char str[]= "lan5ou2015032056", *p = NULL;

//

Char *a[20] = {0};

int count = 0;

int i = 0, j = 0;

Method 1

while (str[i]! = ' + ') {

if (Str[i] >= ' 0 ' && str[i] <= ' 9 ') {

A[J] = (char*) malloc (sizeof (char));

count++;

A[J] = &str[i];

j + +;

//        }

i++;

//    }

for (int i = 0; i < count; i++) {

printf ("%c", * (A[i]));

//    }

Method 2

Get number of numbers

i = 0;

while (str[i]! = ' + ') {

if (Str[i] >= ' 0 ' && str[i] <= ' 9 ') {

count++;

//        }

i++;

//    }

Open Space

Char *num = malloc (count + 1);

Store characters

j = 0;

i = 0;

while (str[i]! = ' + ') {

if (Str[i] >= ' 0 ' && str[i] <= ' 9 ') {

* (num + j) = Str[i];

j + +;

//        }

i++;

//    }

* (num + j) = ' + ';

printf ("%s", num);

Free (num);

num = NULL;

Method 3

i = 0, j = 0;

while (str[i]! = ' + ') {

if (Str[i] >= ' 0 ' && str[i] <= ' 9 ') {

p = realloc (p, sizeof (char));

count++;

* (P + j) = Str[i];

j + +;

//        }

i++;

//    }

//

printf ("Number of digits:%d,%s", count, p);

Free (p);

p = NULL;

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

Storing 3 words means that you need to open 3 space, each time the space will return the corresponding first address, all in order to store 3 addresses, define pointer array storage.

Char *word[3] = {0};

Char temp[20] = {0}; A string that stores the console input

//

for (int i = 0; i < 3; i++) {

printf ("\ninput [%d] name:", i + 1);

scanf ("%s", temp);

Word[i] = malloc (strlen (temp) + 1);//Allocate space dynamically in the heap based on the input string

strcpy (Word[i], temp);

//    }

//

for (int i = 0; i < 3; i++) {

printf ("%s", * (Word + i));

Free (word[i]);

Word[i] = NULL;

//    }

Other memory allocation functions

Calloc (n, size_t) c---Clear one-step cleanup of spatial data, but the cleanup operation is less efficient.

Allocate n size, small space, and zero all bytes in the memory. Allocate n sizes of size space

int *ptr = Calloc (5, 4);

//

Free (PTR);

ptr = NULL;

//

//

ReAlloc Memory reallocation function

Char *pstr = malloc (10);

10 spaces are not enough, reassign 20, not append

Char *pstr1 = realloc (PSTR, 200); How it works: re-allocating new space with the previous start address as a baseline, and finding new space if you find that there is not enough space left. The address returned at this point is not the same as before, and the realloc internal integration of the previous space free operation.

printf ("%p,%p", Pstr, PSTR1);

Free (PSTR1); Just release the realloc space.

PSTR1 = NULL;

Pstr = NULL;

//

Memory manipulation functions

void *memset (void *s, int c, size_t N)

Start initializing n bytes from the memory that s points to C

int memcmp (const void *BUF1, const void *BUF2, unsigned int count)

//

Compare the same memory that BUF1 and Buf2 point to, compare count bytes

void *memcpy (void *dest,const void*source, size_t N)

//

Start copying from the memory that the source points to dest, copy? n bytes

Define two integer pointers, respectively? Use malloc, calloc to allocate space for 3 elements, malloc allocated space? Use Memset to clear zero, random logarithm group into the line assignment random range 1-3, after assignment? Compare two arrays with memcmp? If the same print good! otherwise print failed ...

//

int *IP1 = (int *) malloc (3 * sizeof (int));

int *IP2 = (int *) Calloc (3, 4);

//

memset (ip1, 0, 12); Clear 0 operation

//

for (int i = 0; i < 3; i++) {

* (ip1 + i) = Arc4random ()% 3 + 1;

* (IP2 + i) = Arc4random ()% 3 + 1;

printf ("%d%d\n", * (ip1 + i), * (IP2 + i));

//

//    }

if (memcmp (ip1, IP2, 1) = = 0) {

printf ("good");

}else{

printf ("Failed");

//    }

//

return 0;

}

function implementation

int max (int a, int b) {

Return a > B? A:B;

}

Char string[] = "Welcome to Lanou ios! "; It's possible to put it here, but it's not safe.

Char *getstring () {

Char string[] = "Welcome to Lanou ios!  "; Array string, which is defined inside the function, is a local variable, stored in the stack area, and when the function is executed, the array space is reclaimed by the system. The outside world gets the address and accesses a piece of reclaimed space. Therefore, to return safely, you must ensure that the space is still there after the return.

static char string[] = "Welcome to Lanou ios! "; Set as static array

Char *string = "Welcome to Lanou ios!     "; The return is constant area welcome .... , the first address;

return string;

}

C Language Foundation for iOS development Lesson-10 Dynamic memory Management lesson notes and test exercises

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.