The error code is as follows:
#include <stdio.h>#include<stdlib.h>#include<string.h>voidGet_memory (Char*p,intnum) {P= (Char*) malloc (sizeof(Char)*num);}intMainintargcChar*argv[]) { Char*str =NULL; Get_memory (str, -); strcpy (str,"Hello"); printf ("Resut:%s\n", str); return 0;}
Execution results under Linux
$./ttsegmentation fault
Analysis
After calling the function Get_memory (), p is freed by the system, but because malloc is allocated in the heap, it is released only when the program ends, which results in a memory leak.
Under Linux, because the value of P is changed to 0x00 after a function call, a segment error occurred while executing strcpy due to access to an invalid address.
The correct code, such as (using the two-level pointer method):
#include <stdio.h>#include<stdlib.h>#include<string.h>voidGet_memory (Char**p,intnum) { *p = (Char*) malloc (sizeof(Char)*num);}intMainintargcChar*argv[]) { Char*str =NULL; Get_memory (&STR, -); strcpy (str,"Hello"); printf ("Resut:%s\n", str); return 0;}
The results of the implementation are as follows:
$./Ttresut:hello
Memory leak problem caused by no return function passing in a first-level pointer