①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:
1 | Void ApplyForMem(char *p,int num) |
2 | { |
3 | p=(char*)malloc(sizeof(char)*num); |
4 | return; |
5 | } |
6 | int main() |
7 | { |
8 | char *str=NULL; |
9 | ... |
10 | ApplyForMem(str,300); |
11 | free(str); |
12 | infile.close(); |
13 | return 0; |
14 | } |
解释:ApplyForMem(char *p,int num)是不能传递动态内存的,这样main函数当中Str始终都是NULL。
例2:
1 | #include <unistd.h> |
2 | #include <stdlib.h> |
3 | #include <stdio.h> |
4 | int main() |
5 | { |
6 | char z = *(const char *)0; |
7 | exit(EXIT_SUCCESS); |
8 | } |
解释:(const char *)没有具体指明内存地址,这个写法表示从地址0处取一个字符,而地址0是没有东西的。