存储空间管理

存储空间管理
存储空间的分配和释放
void *calloc(size_t nmemb, size_t size);
void *malloc(size_t size);
void free(void *ptr);
void *realloc(void *ptr, size_t size);

realloc(*ptr,0)=free(*ptr)

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

int main()
{
    int *p;
    p=malloc(sizeof(*p));
    if(p == NULL){
        return -1;
    }
    *p=100;
    printf("%p-->%d\n",p,*p);
    free(p);
    p=NULL;
    *p=20; //别的程序占用时会有问题,无操作权,错误写法,在free后要赋值空指针
    printf("%p-->%d\n",p,*p);
}
-------------------------
0x951010-->100
0x951010-->20

内存泄漏

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

fun(char *ptr,int i){
    ptr=malloc(i);
    strcpy(ptr,"hello");
    puts(ptr);
}
int main()
{
    char *str=NULL;
    int i=32;
    fun(str,i);
    free(str);
}

 

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

char * fun(char *ptr,int i){
    ptr=malloc(i);
    strcpy(ptr,"hello");
    printf("ptr=%p\n", ptr);
    return ptr;
}
int main()
{
    char *str=NULL;
    int i=32;
    str=fun(str,i);
    printf("str=%p\n",str);
    free(str);
}
-------------------
ptr=0x1dbb010
str=0x1dbb010

 

posted @ 2018-02-01 13:36  H&K  阅读(291)  评论(0)    收藏  举报