Dynamic memory allocation

Source: Internet
Author: User


Purpose of dynamic memory allocation: Reasonable use of memory (memory is limited)
Partitioning of the storage area
1, Stack: storage is a stack (advanced post-out) of the structure of storage, local variables (variables defined inside the function) and formal parameters (function parameters) to the stack, call the function, the local variables and formal parameters allocated memory, after the function, the system recalled the memory allocated to this function
2, Heap area: is manually requested by the developer, manual release, requires manual management
3, Static zone (Global Zone): Global variables (variables defined outside the function) and static variables (variables with static modifiers), stored in the static area, once the memory space is opened, will not be released until the end of the program
4, Constant area: storage: integer constant, character constant, floating-point constant, string constant, the contents of the constant area cannot be modified
5, Code area: storing CPU Instructions

int x = ten, y = 5;
int result = MaxValue (x, y);
printf ("%s", getString ());//No output, call function has been reclaimed by the system
//
printf ("%p\n", &x);//Stack Area 0x7fff5fbff84c
static int i = 4;
printf ("%p\n", &i);//static zone 0x100001024
Char *p = "AAA";
printf ("%p\n", p);//constant Area 0x100000f94

Memory allocation in the heap area
Manually open up memory
void *malloc (size);
Return value type: void*, generic type, can be converted to other type pointers, the function returns a pointer
malloc: Name of function
Size: The amount of memory to allocate (in bytes), unsigned integer

Char *p = malloc (7);
strcpy (P, "IPhone");
printf ("%s\n", p);//iphone

*p = 66;
printf ("%s\n", p);//bphone
//
P[3] = ' + ';
printf ("%s\n", p);//BPH
//
//
strcpy (P + 2, "ABCDE");//cross-border
printf ("%s\n", p);
//
strcpy (p, p + 2);//hone
printf ("%s\n", p);
//
printf ("%c\n", * (P + 5));//e



/*
Char *p = malloc (7);//Stack allocation 8 memory space allocated 7 bytes in the heap area the first address of the heap is stored in the contents of the stack area, &p is the first address of the stack area.

strcpy (P, "IPhone"); Constant Zone allocation 7 bytes copied to the corresponding stack area
printf ("%s\n", p);//iphone

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


Char *p1 = "iPhone";//copy is address pointing constant area content cannot be modified
Char string[] = "iPhone";//copy of content copied to the stack area, content in the stack can be modified
*/




for (int i = 0; i < 4; i++) {
static int a = 0;//is initialized only once, running Results 1 2 3 4
a++;
printf ("%d\n", a);
//    }

Creates a stack pointer that points to the first address of the 6 bytes allocated by the heap area
int *p = malloc (6);
Copy the constant area integer constant 10 to the first four bytes of the heap area
*p = 10;
P[1] = 20;//error, out of bounds

Free (void *) frees memory functions
void *: Can accept various types of pointers
Memory leaks: A piece of memory is always occupied, not released
Free will make the malloc request a memory release (re-marked as available)
Free (p);

Apply a memory space randomly assign 10 integers in the array
int *p = malloc (sizeof (int) * 10);
for (int i = 0; i < i++) {
* (p + i) = Arc4random ()% 21 + 10;
printf ("%d", * (P + i));
//    }
Free (p);
After release p now has content
p = null;//Place the pointer empty

int *p = malloc (2);//Memory leak
p = malloc (4);
Free (p);



Has a string that contains numbers, extracts the numbers in them, requires dynamic allocation of memory to save
Tip: Calculate a few numbers first and then open up the space based on the number of numbers
Char string[] = "DFDSFSF2F4GF5HY7G5FD3DS4";
int i = 0, count = 0;
while (* (string + i)! = ' + ') {
if (* (string + i) <= ' 9 ' && * (string + i) >= ' 0 ') {
count++;
//        }
i++;
//    }
Char *p = malloc (sizeof (char) * (count + 1));
//
int k = 0, j = 0;
while (* (string + k)! = ') ' {
if (* (string + k) >= ' 0 ' && * (string + k) <= ' 9 ') {
* (P + j) = * (string + K);
j + +;
//        }
k++;
//    }
Add Terminator
* (P + j) = ' + ';
printf ("%s\n", p);
Free (p);
p = NULL;

Enter 3 words, dynamically allocate memory to save the word, and at the end of the output
Hint: Define a pointer array to hold the data char * word[3] = {0};


char * words[3] = {0};
Char temp[100] = {0};
for (int i = 0; i < 3; i++) {
scanf ("%s", temp);
unsigned long length = strlen (temp) + 1;
Words[i] = malloc (sizeof (char) * length);
strcpy (Words[i], temp);
//    }
for (int i = 0; i < 3; i++) {
Free (words[i]);
Words[i] = NULL;
//    }

void * CALLOC (n, size);
Allocates n size memory space;
N and size are unsigned integer types;
The difference between calloc and malloc: Calloc will keep the data in memory clear and inefficient

int *p = Calloc (5, 4);
Free (p);
p = NULL;


void *realloc (p, size)
Given an address, starting with this address, allocate a size byte of memory
P is pointer, size is unsigned integer
ReAlloc will start from the address P down, if there is a size of unused bytes, directly labeled, and apply; If found not enough, take the other part of the heap area to find a contiguous memory space, if found, the previous application of the memory released, and then point the pointer to the newly found inner space, If not found, returns null

int *p = malloc (2);
printf ("%p\n", p);
p = realloc (P, 4);
printf ("%p\n", p);
Free (p);
p = NULL;



void *memset (void *s, int c, unsigned long N)
Start initializing n bytes from the memory that s points to C

Char *p = malloc (5);
p = memset (P, 66, 10);
printf ("%s\n", p);


void *memcpy (void *dest,const void*source, zize_t N)
Copy n bytes from the memory that the source points to, copying to the Dest
Char string1[] = "IPhone";
Char string2[] = "ABC";
memcpy (string1, string2, 2);//abhone
memcpy (string1 + 3, string2, 2);//iphabe
printf ("%s\n", string1);


int memcmp (const void *BUF1, const void *BUF2, unsigned int count)
Compare BUF1 and buf2 pointing to the same memory, comparing count bytes

int *p1 = malloc (4);
*P1 = 1;
int *P2 = malloc (8);
*P2 = 3;
int result = MEMCMP (P1, P2, 1);
printf ("%d\n", result);


Define two pointers, respectively, with Malloc,calloc to its allocated space to save 3 elements, malloc allocated space with memset zeroed, random array of assigned random range 1-3, after assignment with memcmp compare two arrays, if the same printing good Otherwise print failed


int *p1 = malloc (sizeof (int) * 3);
int *p2 = Calloc (3, 4);
memset (p1, 0, sizeof (int) * 3);
for (int i = 0; i < 3; i++) {
* (P1 + i) = Arc4random ()% 3 + 1;
* (P2 + i) = Arc4random ()% 3 + 1;
//    }
//
if (memcmp (P1, p2, sizeof (int) * 3) = = 0) {
printf ("good!\n");
}else{
printf ("failed...\n");
//    }
Free (p1);
P1 = NULL;
Free (p2);
P2 = NULL;
//

Dynamic memory allocation

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.