内存申请的几个案例.cpp

/*申请内存是在堆区申请,申请之后不会自动消失,new出来的用delete,malloc出来的用free
*对内存的申请要注意
*1.指针的理解;
*2.变量的生存期及作用范围;
*3.良好的动态内存申请和释放习惯;
*文中未对申请空间的结果进行判断,实际使用中应加入if(p == NULL){return },养成良好的习惯
*/

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

using namespace std;

#if 1
void GetMemory1( char *p )
    {
        p = (char *) malloc( 100 );
    }
int main(void)
{
        char *str = NULL;
        GetMemory1( str );
        strcpy( str, "hello world" );
        printf( "%s\n",str );
        printf("\n");
}
#endif
/*
Segmentation fault (core dumped)
上面程序在运行之后,调用GetMemory( str )后, str并未产生变化,依然是NULL.只是改变的str的一个拷贝的内存的变化   
strcpy( str, "hello world" );程序运行到这将产生错误。
*/
#if 1
void GetMemory2(char **p, int num)
    {
    
        *p = (char *) malloc( num );
    }
int main(void)
    {
        char *str=NULL;
        GetMemory2(&str,100);
        strcpy(str,"hello world");
        printf(str);
        free(str);
        printf("\n");
    }
#endif
//Right
#if 1
char* GetMemory3()
    {
        char* p=(char*)malloc(100);
        return p;
    }
int main(void){
        char *str=NULL;
        str=GetMemory3();
        strcpy(str,"hello world");
        printf(str);
        free(str);
        printf("\n");
}
#endif
//Right
#if 1
char* GetMemory4(void)
{
    char p[] = "hello world";
    return p;
}
int main( void )
{
        char *str = NULL;
        str = GetMemory4();
        printf( str );
}
#endif
//error:address of local variable ‘p’ returned
//p[]数组为函数内的局部自动变量,在函数返回后,内存已经被释放。

#if 1
char* GetMemory5(char *&p, int num)
    {
        p = new char[num];
        return p;
    }
int main(void){
    char *str ;
    GetMemory5(str, 100);
    strcpy(str, "hello");
    cout << str << endl;
    delete[] str;
    return 0;
}
#endif
//Right
#if 1
int main( void )
    {
        char *str = (char *) malloc(100);
        strcpy( str, "hello" );
        printf( str );
        printf("\n");
        free( str );
    }
//Right    
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值