malloc
malloc
是 C 标准库中的一个函数,用于动态分配内存。它的函数声明如下:
void* malloc(size_t size);
malloc
接受一个参数 size
,表示要分配的内存块的大小(以字节为单位)。它会在堆上分配一个大小为 size
字节的连续内存块,并返回一个指向该内存块的指针。
如果内存分配成功,malloc
返回一个指向分配内存的指针。如果分配失败,则返回 NULL
。
使用 malloc
的示例:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr;
int num_elements = 5;
// 分配包含 5 个整数的内存块
ptr = (int*)malloc(num_elements * sizeof(int));
if (ptr == NULL) {
printf("内存分配失败\\n");
return 1;
}
// 使用分配的内存
for (int i = 0; i < num_elements; i++) {
ptr[i] = i; // 为数组赋值
}
// 输出分配的内存
for (int i = 0; i < num_elements; i++) {
printf("%d ", ptr[i]); // 输出 0 1 2 3 4
}
// 释放内存
free(ptr);
return 0;
}
在上面的示例中,malloc
用于分配包含 5 个整数的内存块。之后,我们检查是否分配成功,然后使用该内存。最后,在不再需要时,使用 free
函数释放内存块。
realloc
realloc
是 C 标准库中的一个函数,用于重新分配先前分配的内存块的大小。其函数声明如下:
void* realloc(void* ptr, size_t size);
realloc
接受两个参数:
ptr
:指向先前由malloc
、calloc
或realloc
返回的内存块的指针。如果ptr
是NULL
,则realloc
的行为类似于malloc
,即分配新的内存块。size
:重新分配内存块的新大小(以字节为单位)。