Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to allocate C++ dynamic memory in C language programming

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to allocate dynamic memory of C++ in C language programming". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn how to allocate the dynamic memory of C++ in C language programming.

Catalogue

Dynamic memory management

Why is there dynamic memory allocation?

Introduction of dynamic memory function

Malloc apply for space and free release space

Free memory by borrowing and returning free

Calloc request memory

Realloc resizes dynamic memory

Considerations for the use of realloc

Of course, realloc can also directly open up space.

Common dynamic memory errors

1. Dereferencing of NULL pointer

two。 Cross-border access to dynamic opening up space

3. Use free release for non-dynamic opening memory

4. Use free to free up a piece of dynamic memory

5. Release the same piece of dynamic memory multiple times

6. Dynamically open up memory to forget to release (memory leak)

A few interview questions

Topic 1

Topic 2

Topic 3

Topic 4

The memory Development of Cmax Clipper + Program

There are several areas of memory allocation for the CAccord + program:

Why there is dynamic memory allocation in dynamic memory Management

What kind of memory development methods have we mastered so far?

/ / create a variable int val = 20; / / Local variable opens up 4 bytes in stack space int g_val = 10; / / Global variable opens 4 bytes in static area / / creates an array char g_arr [10] = {0}; / / Local region opens up 10-byte continuous space char g_arr [5] = {0} in stack space / / the global zone opens up a 5-byte contiguous space in the static zone space

But the above way of opening up space has two characteristics:

1. The size of the space opening is fixed.

two。 When an array is declared, it must specify the length of the array, and the memory it requires is allocated at compile time.

But the need for space is not just the case mentioned above. Sometimes we don't know the amount of space we need until the program is running, so the way the array opens up space at compile time can't be satisfied. At this point, you can only try dynamic memory development.

C99 supports variable-length arrays, but now many compilers do not support c99, even vs, so there is the concept of dynamic memory.

Introduction of dynamic memory function malloc application space and free free space

C language provides a function of dynamic memory development.

Void* malloc (size_t size)

This function requests a continuously available space from memory and returns a pointer to that space.

1. If the opening is successful, a pointer to the opened space is returned.

two。 If opening fails, a NULL pointer is returned, so the return value of malloc must be checked.

3. The type of the return value is void, so the malloc function does not know the type of opening up the space, which is decided by the user when using it. *

4. If the parameter size is 0malloc, the behavior is not defined by the standard, depending on the compiler.

# include#include#include#includeint main () {/ / request 10 shaping spaces from memory int* p = (int*) malloc (10 * sizeof (int)); if (p = = NULL) {/ / print out printf ("% s", strerror (errno)) } else {/ / normal usage space int I = 0; for (I = 0; I

< 10; i++) { *(p + i) = i;//在找下标为i的元素 } for (i = 0; i < 10; i++)//再把每个元素打印出来 { printf("%d ", *(p + i)); } } return 0;} 那我们可不可以看开辟失败的呢 我们可以用INT_MAX(他是整形最大),一个超级大的数字

Free memory by borrowing and returning free

The free function is used to free dynamically opened memory.

1. If the space pointed to by the parameter ptr is not dynamically opened up, then the behavior of the free function is undefined.

two。 If the argument ptr is a NULL pointer, the function does nothing.

Be careful

Malloc and free are used in pairs, who opens up and releases.

Calloc request memory

Open an array in memory and change all the elements to zero

The function is to open up a space for num elements the size of size, and initialize each byte of the space to 0.

The only difference from the function malloc is that calloc initializes each byte of the requested space to all zeros before returning the address

Realloc resizes dynamic memory

Of course, we can apply for space, but will we encounter that there is not enough space for application? we want to add some, and when we get bigger, we want to get rid of some.

Considerations for the use of realloc

1. If there is enough memory space to append after the space p points to, append it directly and return p

two。 If there is not enough memory space to append after the space p points to, the realloc function will find a new memory area, open up a space that meets the needs, copy the data in the original memory back, free up the old memory space, and finally return the address of the newly opened memory space.

3. But there is also a big problem, which is to open up INT_MAX and use the new variable ptr to receive the realloc return value.

Of course, realloc can also directly open up space.

Common dynamic memory errors 1. Dereferencing of the NULL pointer # include#includeint main () {int* p = (int*) malloc (40); / / if it is not successful, there will be a big problem int I = 0; for (I = 0; I < 10; iSum +) {* (p + I) = I;} free (p); p = NULL; return 0;}

Therefore, in order to prevent the success of dynamic memory, we need to make a judgment.

two。 Cross-border access to dynamic opening up space # include#include#include#includeint main () {int* p = (int*) malloc (5*sizeof (int)); if (p = = NULL) / / here I do judge whether {printf ("% s", strerror (errno));} else {int I = 0 For (I = 0; I < 10; iSum +) / / but here I access the spaces of 10 integers {* (p + I) = I;}} free (p); p = NULL; return 0;}

3. Use free to release int main () {int a = 0; int* p = & a; * p = 20; free (p); p = NULL; return 0;} for non-dynamic open memory

4. Use free to release a portion of dynamic memory open up # include#include#include#includeint main () {int* p = (int*) malloc (40); if (p = = NULL) {return 0 for (I = 0; I < 10) (free +) {* paired + = iPlacement / this + + is where bug is located} / / Recycling space free (p); p = NULL; return 0;}

As long as p is not the first address of the space applied for, everything else is wrong.

5. Release # include#include#include#includeint main () {int* p = (int*) malloc (40) for the same dynamic memory multiple times; if (p = = NULL) {return 0;} / use / / release free (p); / /. Free (p); return 0;}

6. Dynamically open memory to forget to release (memory leak) # include#include#include#includeint main () {while (1) {malloc (100);} return 0;}

Several interview questions 1void GetMemory (char* p) {p = (char*) malloc;} void Test (void) {char* str = NULL; GetMemory (str); strcpy (str, "hello world"); printf (str); / / this is the same as printf ("% s", str); it is the same} int main () {Test (); return 0;}

Ask what the result will be if you run the Test function

Correct modification

# include#include#include#includevoid GetMemory (char* * p) {* p = (char*) malloc;} void Test (void) {char* str = NULL; GetMemory (& str); strcpy (str, "hello world"); printf (str); / / this is the same free (str) as printf ("% s", str); / / release str = NULL after use } int main () {Test (); return 0;}

Title 2char* GetMemory (void) {char p [] = "hello world"; return p;} void Test (void) {char* str = NULL; str = GetMemory (); printf (str);} int main () {Test (); return 0;}

What will be the result of running Test function?

Output random value

Correct modification

Since p has been destroyed, we can ask him not to destroy it and extend its life cycle with static.

Char* GetMemory (void) {static char p [] = "hello world"; return p;} void Test (void) {char* str = NULL; str = GetMemory (); printf (str);} int main () {Test (); return 0;}

Title 3void GetMemory (char * * p, int num) {* p = (char *) malloc (num);} void Test (void) {char * str = NULL;GetMemory (& str, 100); strcpy (str, "hello"); printf (str);}

This question is basically the same as the first one, but it only has the error of memory leak.

Correct modification

# include#includevoid GetMemory (char** p, int num) {* p = (char*) malloc (num);} void Test (void) {char* str = NULL; GetMemory (& str, 100); strcpy (str, "hello"); printf (str); free (str); / / release after use to prevent memory leaks str = NULL;} int main () {Test () Return 0;}

Title 4void Test (void) {char* str = (char*) malloc; strcpy (str, "hello"); free (str); if (str! = NULL) {strcpy (str, "world"); printf (str);}}

The problem is very big to print out the result.

Correct modification

# include#include#includevoid Test (void) {char* str = (char*) malloc; strcpy (str, "hello"); free (str); / / what is examined here is that the release of free does not make str NULL, so the following if judgment has no effect. If you make it useful, let str be NULL str = NULL. If (str! = NULL) {strcpy (str, "world"); printf (str);}} int main () {Test (); return 0;}

The real purpose of this question is to get you not to print anything.

The memory Development of Cmax Clipper + Program

There are several areas of memory allocation for the CAccord + program:

Stack: the storage units of local variables within the function can be created on the stack when the function is executed, and these storage units are automatically released at the end of the function execution. The stack memory allocation operation is built into the instruction set of the processor, which is very efficient, but the allocated memory capacity is limited. The stack area mainly stores local variables, function parameters, return data, return address and so on.

Heap: generally allocated and released by programmers, if programmers do not release, the program may be reclaimed by OS at the end of the program. The mode of allocation is similar to a linked list.

The data segment (static zone) (static) stores global variables and static data. It will be released by the system at the end of the program.

Code snippet: binary code that stores the body of a function (class member functions and global functions).

At this point, I believe you have a deeper understanding of "how to allocate C++ dynamic memory in C language programming". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report