#include<stdio.h>#include<stdlib.h>#include<string.h>intmain(int argc,charconst*argv[]){int i=0;while(i<204800){malloc(1024000);
i++;}printf("Press any key to continue . . . ");getchar();return0;}
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 20041.2g 3.7g 412 S 0.02.963:54.65 java8273 root 20014.3g 2.1g 1520 S 0.31.646:07.03 java27834 informix 10-10 1355m 1.1g 1.1g S 0.00.90:01.90 oninit
#28139 informix 20 0 195g 800m 360 S 0.0 0.6 0:00.48 a.out13536 gbasedbt 10-1054.4g 650m 645m S 0.00.538:37.62 oninit
13528 gbasedbt 10-1054.4g 637m 633m S 0.00.51:00.32 oninit
malloc 分配连续空间(就像数组)
下面这两种写法都是正确的。
只是注意如果移动了原指针位置,需要复原指针位置,才能再次循遍历该量内存段。
#include<stdio.h>#include<stdlib.h>#include<string.h>intmain(int argc,charconst*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;return0;}
#include <stdio.h>#include <stdlib.h>#include <string.h>
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;return0;}