malloc()和free()在C / C ++中如何工作?
malloc()
该函数malloc()用于分配请求的字节大小,并返回指向已分配内存的第一个字节的指针。如果失败,则返回空指针。
这是malloc()C语言的语法,
pointer_name = (cast-type*) malloc(size);
这里,
pointer_name- 给指针的任何名称。
cast- type-要通过其强制转换分配的内存的数据类型malloc()。
大小 -以字节为单位分配的内存大小。
这是malloc()C语言的示例,
示例
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
return 0;
}输出结果
这是输出
Enter elements of array : 32 23 21 8 Sum : 84
自由()
该函数free()用于通过释放分配的内存malloc()。它不会更改指针的值,这意味着它仍指向相同的存储位置。
这是free()C语言的语法,
void free(void *pointer_name);
这里,
pointer_name-给指针的任何名称。
这是free()C语言的示例,
示例
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
free(p);
return 0;
}输出结果
这是输出
Enter elements of array : 32 23 21 28 Sum : 104