About returning dynamic memory in functions

1 #include <iostream>
 2 using namespace std;
 3 
 4 void GetMemeory(char* p)
 5 {
 6     p=(char*)malloc(sizeof(char)*100);
 7 }
 8 
 9 int main()
10 {
11     char *str=NULL;
12     GetMemeory(str);
13     strcpy(str,"Thunder");
14     strcat(str,"Downloader");
15     printf(str);
16     system("pause");
17     return 0;
18 }

The output we expect is: ThunderDownloader

However, when we run this code, we find that the program crashes.

 

In fact, it is not difficult to find that when we pass in str into the GetMemeory() function, this function creates a temporary

the pointer variable slice p, and then point it to NULL. Then we dynamically allocate memory for the temporary pointer variable p, note that when we return

The entire temporary pointer variable is freed because its memory is allocated in stack memory. But the memory address of str and the temporary variable we passed in before

The memory addresses are not the same. So at this time str cannot obtain the memory allocated in the function GetMemmory, so the following string copy and link operations

will cause the program to crash.

Assume that str itself memory is 0x123, the memory of temporary pointer variable p is 0x456, and the starting address of dynamically allocated memory is 0x789

When the GetMemory function finishes, p is freed, and there are no more pointers to the dynamically allocated memory. Also str is impossible

Get the address of this dynamically allocated memory. So it also caused a memory leak.

We can solve this problem in two ways:

One is a secondary pointer:

 

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void GetMemeory(char** p)
 5 {
 6     (*p)=(char*)malloc(sizeof(char)*100);
 7 }
 8 
 9 int main()
10 {
11     char *str=NULL;
12     GetMemeory(&str);
13     strcpy(str,"Thunder");
14     strcat(str,"Downloader");
15     printf(str);
16     system("pause");
17     return 0;
18 }

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326393009&siteId=291194637