C-Language dynamic memory application and release

Source: Internet
Author: User

What is the application and release of dynamic memory?

When a program runs to a variable that needs to be dynamically allocated, it must request to the system to obtain a chunk of the heap in the required amount of storage space for storing the variable. When the variable is no longer used, that is, the end of its life, to explicitly release the storage space it occupies, so that the system can re-allocate the heap space, so that the use of limited resources reuse.

The following describes the dynamic memory request and the freed function

1.malloc function

in the C language, use the malloc function to request memory. The function prototypes are as follows:

#include <stdlib.h>

void *malloc (size_t size);

The parameter size represents the number of bytes of memory that need to be dynamically requested , and if the memory request succeeds, the function returns the starting address of the requested memory, and if the request fails, returns NULL, you should pay attention to the following points when using this function

1. Only concerned about the size of the application memory, the parameters of the function is very simple, only the size of the request memory, the unit is bytes

2. The application is a contiguous memory, the function must be to apply for a contiguous interval, may apply to the memory than the actual application of large, but also may not be able to apply, if the application fails, then return null

3. The return value type is void*, the return value of the function is void*, is not a pointer to a specific type, it can be understood that the function simply applies memory, what type of data is stored in memory, there is no requirement, therefore, the return value is void*, actual programming, according to the actual situation will void* Convert to required type of pointer

4. Display initialization, note: The heap area is not automatically initialized at the time of allocation (including clear 0 ), so the initialization that needs to be displayed in the program

2.free function

The memory allocated on the heap area needs to be Free The function displays the release. The function prototypes are as follows:

#include <stdlib.h>

void free (void *ptr);

The function's parameter, PTR, refers to the starting address of the memory that needs to be freed . The function does not return a value. With this function, there are also the following points to note:

(1) The starting address of the memory must be provided. When you call this function, you must provide the starting address of the memory, cannot provide a partial address, and releasing part of the memory is not allowed. Therefore, the pointer value returned by malloc must be saved, and if lost, the allocated heap space cannot be reclaimed, which is called a memory leak.

(2) malloc paired with free. The compiler is not responsible for the release of dynamic memory and requires the programmer to display the release. Therefore,malloc is paired with free and avoids memory leaks.

The sample program is as follows:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int *get_memory (int n)

{

int *p, I;

if ((p = (int *) malloc (n * sizeof (int))) = = NULL)

{

printf ("malloc error\n");

return p;

}

memset (p, 0, n * sizeof (int));

for (i = 0; i < n; i++)

P[i] = i+1;

return p;

}

int main ()

{

int n, *p, I;

printf ("Input n:");

scanf ("%d", &n);

if ((p = get_memory (n)) = = = NULL) {

return 0;

}

for (i = 0; i < n; i++) {

printf ("%d", p[i]);

}

printf ("\ n");

Free (p);

p = NULL;

return 0;

}

The results of the program execution are as follows:

[Email protected]:~/book/ch10$ cc Malloc.c-wall

[Email Protected]:~/book/ch10$./a.out

Input N:10

1 2 3 4 5 6 7 8 9 10

This program demonstrates the standard usage of dynamic memory. the application of dynamic memory is done through a pointer function . When the memory request is made, it is determined whether the application succeeds and after the memory is initialized. In the main melody function, dynamic memory is still accessible and freed with the free function when memory is no longer being accessed.

(3) Repeated releases are not allowed. Repeated releases of the same space are also dangerous because the space may have been allocated separately. In the above program, if the heap space is freed two times (two times for free (p)), the following results appear.

[Email protected]:~/book/ch10$ cc Malloc.c–wall

[Email Protected]:~/book/ch10$./a.out

Input N:1

1

GLIBC detected * * *./a.out:double free or Corruption (fasttop): 0x08f1a008 * * *

======= BackTrace: =========

/lib/libc.so.6 (+0x6c501) [0x687501]

/lib/libc.so.6 (+0X6DD70) [0X688D70]

/lib/libc.so.6 (CFREE+0X6D) [0x68be5d]

./a.out[0x804861e]

/lib/libc.so.6 (__libc_start_main+0xe7) [0x631ce7]

./a.out[0x8048471]

======= Memory Map: ========

0061b000-00772000 R-xp 00000000 08:01 1048623/lib/libc-2.12.1.so

00772000-00773000---p 00157000 08:01 1048623/lib/libc-2.12.1.so

00773000-00775000 r--p 00157000 08:01 1048623/lib/libc-2.12.1.so

00775000-00776000 rw-p 00159000 08:01 1048623/lib/libc-2.12.1.so

00776000-00779000 Rw-p 00000000 00:00 0

008e1000-008fb000 R-xp 00000000 08:01 1048657/lib/libgcc_s.so.1

008fb000-008fc000 r--p 00019000 08:01 1048657/lib/libgcc_s.so.1

008fc000-008fd000 rw-p 0001a000 08:01 1048657/lib/libgcc_s.so.1

00a8f000-00aab000 R-xp 00000000 08:01 1048599/lib/ld-2.12.1.so

00aab000-00aac000 r--p 0001b000 08:01 1048599/lib/ld-2.12.1.so

00aac000-00aad000 rw-p 0001c000 08:01 1048599/lib/ld-2.12.1.so

00b6c000-00b6d000 R-xp 00000000 00:00 0 [VDSO]

08048000-08049000 R-xp 00000000 08:01 1079938/home/linux/book/ch10/a.out

08049000-0804a000 R--p 00000000 08:01 1079938/home/linux/book/ch10/a.out

0804a000-0804b000 rw-p 00001000 08:01 1079938/home/linux/book/ch10/a.out

08f1a000-08f3b000 Rw-p 00000000 00:00 0 [Heap]

b7700000-b7721000 Rw-p 00000000 00:00 0

b7721000-b7800000---P 00000000 00:00 0

b7815000-b7816000 Rw-p 00000000 00:00 0

b7823000-b7827000 Rw-p 00000000 00:00 0

bf9a5000-bf9c6000 Rw-p 00000000 00:00 0 [Stack]

Aborted

(4) Free only heap space can be freed. Like the code area, global variables and static variable area, the variables on the stack are not required to be released by the programmer, the space on these areas cannot be freed through the free function, or an error occurs when executed.

The sample program is as follows:

#include <stdlib.h>

int main ()

{

int a[10] = {0};

Free (a);

return 0;

}

The results of the program execution are as follows:

[Email protected]:~/book/ch10$ cc Free.c–o Free-wall

free.c:in function ' main ':

Free.c:7: Warning:attempt to free a Non-heap object ' a '

You can see that there is a warning that frees up space on a non-heap. If you forcibly execute the program, the following results appear:

[Email Protected]:~/book/ch10$./a.out

Segmentation fault

3. Wild Hands

The wild pointer refers to a pointer to "junk" memory, not NULL pointer . The "Wild pointer " appears mainly for the following reasons:

( 1 The pointer variable is not initialized. Pointer variables, like other variables, are indeterminate if not initialized. In other words, there is no initialized pointer, pointing to the garbage memory, very dangerous.

The sample program is as follows:

#include <stdio.h>

int main ()

{

int *p;

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

*p = 10;

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

return 0;

}

The results of the program execution are as follows:

[Email protected]:~/book/ch10$ cc P.c–o P-wall

[Email protected]:~/book/ch10$./p

1416572

Segmentation fault

(2) pointer P was Free after that, it is not placed as NULL . The free function frees the memory that the pointer is pointing to, making the memory the RAM. However, the function does not make the contents of the pointer itself clear. The pointer still points to the dynamic memory that has been freed, which is very dangerous. a programmer with a slight negligence would mistakenly assume that it was a legitimate pointer. It is possible to access dynamic memory through pointers again. In fact, this time the memory is already garbage memory, about the wild pointer will cause what kind of consequences, it is difficult to estimate. If the memory is still idle, the program may temporarily run normally, if the memory is again allocated, and through the wild pointer to the memory of the write operation, the original legitimate data will be overwritten, then, the impact of the wild pointer will be impossible to estimate.

The sample program is as follows:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main ()

{

int n = 5, *p, I;

if ((p = (int *) malloc (n * sizeof (int))) = = NULL)

{

printf ("malloc error\n");

return 0;

}

memset (p, 0, n * sizeof (int));

for (i = 0; i < n; i++)

{

P[i] = i+1;

printf ("%d", p[i]);

}

printf ("\ n");

printf ("p=%p *p=%d\n", p, *p);

Free (p);

printf ("After free:p=%p *p=%d\n", p, *p);

*p = 100;

printf ("p=%p *p=%d\n", p, *p);

return 0;

}

The results of the program execution are as follows:

[Email protected]:~/book/ch10$cc test.c–o Test-wall

[Email Protected]:~/book/ch10$./test

1 2 3) 4 5

p=0x92cf008 *p=1

After free:p=0x92cf008 *p=0

p=0x92cf008 *p=100

The program was deliberately executed in the " Free (p) "After that, through the wild pointer P The dynamic memory is read and written, the program executes normally and is expected. As already analyzed, after the memory is released, if you continue to access or even modify, the consequences are unpredictable.

( 3 The pointer operation goes beyond the scope of the variable. Pointer operation, due to a logical error, resulting in pointer access to illegal memory, this situation is not easy, can only rely on the programmer good Coding style, has a solid basic skills. The following shows a situation where a pointer operation is out of bounds:

The sample program is as follows:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main ()

{

int a[5] = {1, 9, 6, 2, ten}, *p, I, N;

n = sizeof (a)/sizeof (n);

p = A;

for (i = 0; I <= N; i++)

{

printf ("%d", *p);

p++;

}

printf ("\ n");

*p = 100;

printf ("*p=%d\n", *p);

return 0;

}

The results of the program execution are as follows:

[Email protected]:~/book/ch10$ cc Test.c–o Test-wall

[Email Protected]:~/book/ch10$./test

1 9 6 2 10 5

*p=100

The program intentionally made two errors, one is the condition of the For loop " I <= n ", P The pointer points to a space outside the array. The second is "*p =", the illegal memory is written operation.

( 4 ) do not return pointers to stack memory . The pointer function returns a pointer. In the main melody function, it is often through the returned pointer that it continues to access the pointed memory. Therefore, the pointer function cannot return the starting address of the stack memory because the stack memory is freed at the end of the function.

C-Language dynamic memory request and release

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.