LINUX期末复习---内存管理

①malloc函数
原型:extern void *malloc(unsigned int num_bytes);
头文件:#include <alloc.h>
功能:分配长度为num_bytes字节的内存块。
说明:如果分配成功则返回指向被分配内存的指针,否则返回空指针NULL。当内存不再使用时,应使用free()函数将内存块释放。
举例
#include <syslib.h>
#include <alloc.h>
main()
{
    char *p;
    clrscr(); // clear screen
    p=(char *)malloc(100);
    if(p)
        printf("Memory Allocated at: %x",p);
    else
        printf("Not Enough Memory!/n");
    free(p);
    return 0;
}

② calloc函数
原型:extern void *calloc(int num_elems, int elem_size);
头文件:#include <alloc.h>
功能:为具有num_elems个长度为elem_size元素的数组分配内存。
说明:如果分配成功则返回指向被分配内存的指针,否则返回空指针NULL。当内存不再使用时,应使用
free()函数将内存块释放。
举例
#include <syslib.h>
#include <alloc.h>
main()
{
    char *p;
    clrscr(); // clear screen
    p=(char *)calloc(100,sizeof(char));
    if(p)
       printf("Memory Allocated at: %x",p);
    else
       printf("Not Enough Memory!/n");
    free(p);
    return 0;
}

③realloc函数
原型:extern void *realloc(void *mem_address, unsigned int newsize);
头文件:#include <alloc.h>
功能:改变mem_address所指内存区域的大小为newsize长度。
说明:如果分配成功则返回指向被分配内存的指针,否则返回空指针NULL。当内存不再使用时,应使用   free()函数将内存块释放。
举例
#include <syslib.h>
#include <alloc.h>
main()
{
    char *p;
    clrscr(); // clear screen
    p=(char *)malloc(100);
    if(p)
        printf("Memory Allocated at: %x",p);
    else
        printf("Not Enough Memory!/n");
    p=(char *)realloc(p,256);
    if(p)
        printf("Memory Reallocated at: %x",p);
    else
        printf("Not Enough Memory!/n");
    free(p);
    return 0;
}
(分配出来的起址都是一样的)

④内存错误分析

例1:

Void  ApplyForMem(char *p,int num)
{
     p=(char*)malloc(sizeof(char)*num);
     return;
}
int  main()
{
   char *str=NULL;
   ...
10     ApplyForMem(str,300);
11     free(str);
12     infile.close();
13     return 0;
14  }

解释:ApplyForMem(char *p,int num)是不能传递动态内存的,这样main函数当中Str始终都是NULL。

例2:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main() 
{
    char z = *(const char *)0;
    exit(EXIT_SUCCESS);
}

解释:(const char *)没有具体指明内存地址,这个写法表示从地址0处取一个字符,而地址0是没有东西的。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值