Memory leak problem caused by no return function passing in a first-level pointer

Source: Internet
Author: User

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 (&AMP;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

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.