malloc
- malloc 分配指定字节,返回空类型的指针。
- malloc 分配的内存在堆上。
- malloc 分配的内存不会自动初始化。
- malloc 分配的内存要记得手动free回收,不然会内存泄漏。
- memset(ptr,0,size) 这样可以初始化内存为0。
- calloc(num, size) 就是对malloc的封装,它封装了初始化0值操作。
- memcpy(ptr1目标, ptr2源, num) 拷贝内存段2中的num个元素到内存段1中。
- realloc 就是对memcpy的封装,如何你原来申请的内存不够用了,用realloc帮你申请新的内存,它帮忙拷贝和释放老内存段。给它个原指针名称和新的大小即可。
- linux上用top看,我c程序申请195G内存,但是实际分配的物理内存是800M,top里面用Shift+M是按照物理内存排序。
#include
#include
#include
int main(int argc, char const *argv[])
{
int i=0;
while (i<204800)
{
malloc(1024000);
i++;
}
printf("Press any key to continue . . . ");
getchar();
return 0;
}
top - 20:16:41 up 68 days, 9:15, 5 users, load average: 0.00, 0.00, 0.00
Tasks: 990 total, 1 running, 989 sleeping, 0 stopped, 0 zombie
Cpu(s): 0.1%us, 0.0%sy, 0.0%ni, 99.9%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Mem: 132050992k total, 131318752k used, 732240k free, 54260k buffers
Swap: 4194300k total, 18446744073089984732k used, 623761184k free, 121672372k cached
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
9172 root 20 0 41.2g 3.7g 412 S 0.0 2.9 63:54.65 java
8273 root 20 0 14.3g 2.1g 1520 S 0.3 1.6 46:07.03 java
27834 informix 10 -10 1355m 1.1g 1.1g S 0.0 0.9 0:01.90 oninit
13536 gbasedbt 10 -10 54.4g 650m 645m S 0.0 0.5 38:37.62 oninit
13528 gbasedbt 10 -10 54.4g 637m 633m S 0.0 0.5 1:00.32 oninit
malloc 分配连续空间(就像数组)
- 下面这两种写法都是正确的。
- 只是注意如果移动了原指针位置,需要复原指针位置,才能再次循遍历该量内存段。
#include
#include
#include
int main(int argc, char const *argv[])
{
int i = 0;
int n = 0;
int *p = NULL;
printf("Enter the number of elements: ");
scanf("%d", &n);
p = (int *)malloc(sizeof(int) * n);
if (p == NULL)
{
printf("Memory allocation failed. Exiting the program.\n");
exit(1);
}
printf("Enter the elements: \n");
for (i = 0; i < n; i++)
{
printf("Enter element %d: ", i + 1);
scanf("%d", &p[i]);
}
for (i = 0; i < n; i++)
{
printf("Element %d is %d\n", i + 1, p[i]);
}
free(p);
p = NULL;
return 0;
}
int main(int argc, char const *argv[])
{
int i = 0;
int n = 0;
int *p = NULL;
int *begin = NULL;
printf("Enter the number of elements: ");
scanf("%d", &n);
p = (int *)malloc(sizeof(int) * n);
begin = p;
if (p == NULL)
{
printf("Memory allocation failed. Exiting the program.\n");
exit(1);
}
printf("Enter the elements: \n");
for (i = 0; i < n; i++)
{
printf("Enter element %d: ", i + 1);
scanf("%d", p++);
}
p = begin;
for (i = 0; i < n; i++)
{
printf("Element %d is %d\n", i + 1, *p++);
}
p = begin;
free(p);
p = NULL;
begin = NULL;
return 0;
}
- 程序的本质是:代码段,数据段,BBS段,堆内存,栈内存,程序参数环境变量。
- 栈内存,从高地址往低地址压栈,函数局部变量,函数退出时自动释放。
- 堆内存,函数退出时不会自动释放,主程序退出才会释放。
- 有了内存地址,有了内存结构,就有了以切。