malloc函数

转载自:http://blog.csdn.net/xw13106209/article/details/4962479
程序员


1、原型:extern void *malloc(unsigned int num_bytes);数组

头文件:#include <malloc.h> 或 #include <alloc.h> (注意:alloc.h 与 malloc.h 的内容是彻底一致的。)函数

功能:分配长度为num_bytes字节的内存块ui

说明:若是分配成功则返回指向被分配内存的指针,不然返回空指针NULL。spa

当内存再也不使用时,应使用free()函数将内存块释放。操作系统

 

举例:
.net

[c-sharp] view plain copy
  1. #include<stdio.h>  
  2. #include<malloc.h>  
  3. int main()  
  4. {  
  5.     char *p;  
  6.    
  7.     p=(char *)malloc(100);  
  8.     if(p)  
  9.         printf("Memory Allocated at: %x/n",p);  
  10.     else  
  11.         printf("Not Enough Memory!/n");  
  12.     free(p);  
  13.     return 0;  
  14. }  

 

 

2、函数声明(函数原型): 指针

  void *malloc(int size); blog

  说明:malloc 向系统申请分配指定size个字节的内存空间。返回类型是 void* 类型。void* 表示未肯定类型的指针。C,C++规定,void* 类型能够强制转换为任何其它类型的指针。这个在MSDN上能够找到相关的解释,具体内容以下:ip

     

malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void, use a type cast on the return value. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object. If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.

3、malloc与new的不一样点

  从函数声明上能够看出。malloc 和 new 至少有两个不一样: new 返回指定类型的指针,而且能够自动计算所须要大小。好比:

      int *p;

  p = new int; //返回类型为int* 类型(整数型指针),分配大小为 sizeof(int);

  或:

  int* parr;

  parr = new int [100]; //返回类型为 int* 类型(整数型指针),分配大小为 sizeof(int) * 100;

 

    而 malloc 则必须由咱们计算要字节数,而且在返回后强行转换为实际类型的指针。

    int* p;

  p = (int *) malloc (sizeof(int));

 

  第1、malloc 函数返回的是 void * 类型,若是你写成:p = malloc (sizeof(int)); 则程序没法经过编译,报错:“不能将 void* 赋值给 int * 类型变量”。因此必须经过 (int *) 来将强制转换。

  第2、函数的实参为 sizeof(int) ,用于指明一个整型数据须要的大小。若是你写成:

  int* p = (int *) malloc (1);

  代码也能经过编译,但事实上只分配了1个字节大小的内存空间,当你往里头存入一个整数,就会有3个字节无家可归,而直接“住进邻居家”!形成的结果是后面的内存中原有数据内容所有被清空。

  malloc 也能够达到 new [] 的效果,申请出一段连续的内存,方法无非是指定你所须要内存大小。

  好比想分配100个int类型的空间:

  int* p = (int *) malloc ( sizeof(int) * 100 ); //分配能够放得下100个整数的内存空间。

  另外有一点不能直接看出的区别是,malloc 只管分配内存,并不能对所得的内存进行初始化,因此获得的一片新内存中,其值将是随机的。

  除了分配及最后释放的方法不同之外,经过malloc或new获得指针,在其它操做上保持一致。

 

 总结:

malloc()函数其实就在内存中找一片指定大小的空间,而后将这个空间的首地址范围给一个指针变量,这里的指针变量能够是一个单独的指针,也能够是一个数组的首地址,这要看malloc()函数中参数size的具体内容。咱们这里malloc分配的内存空间在逻辑上连续的,而在物理上能够连续也能够不连续。对于咱们程序员来讲,咱们关注的是逻辑上的连续,由于操做系统会帮咱们安排内存分配,因此咱们使用起来就能够当作是连续的。

相关文章
相关标签/搜索