C中的malloc()和calloc()
时间:2020-02-23 14:32:04 来源:igfitidea点击:
我们使用malloc()和calloc()在堆上动态分配内存。
对于程序,静态内存分配是在其堆栈上完成的,其中为特定变量保留了预定义的内存量。
如果变量的大小动态变化,我们需要确保可以动态管理其内存。
这是可以使用malloc()和calloc()以及realloc()和free()函数的地方。
让我们了解如何使用这些功能来管理堆。
malloc()和calloc()的语法
malloc()用于在堆上分配用户定义的字节数。
由于我们将内存位置与指针相关联,因此这还将返回指向该内存位置的指针。
void* malloc(size_t size);
返回指针后,这将在堆上分配size字节。
calloc()类似,但是它不仅分配内存,而且将它们设置为零。
void* calloc(int num_blocks, size_t block_size);
这为指针分配了" num_blocks",每个都有" block size",并将块设置为零。
如果由于某种原因内存分配失败,则malloc()和calloc()都将返回NULL指针。
我们可以将void *指针转换为我们选择的指针,例如int,float等。
注意:这是C标准库的一部分。
因此,我们必须包含头文件<stdlib.h>。
现在我们已经了解了语法,下面通过一些示例让我们更加清楚地了解它们。
malloc()的示例
首先让我们看一下malloc()函数的示例。
#include <stdio.h>
#include <stdlib.h>
int main() {
//Allocating memory dynamically on the heap
//for an integer, which returns an int* pointer
int* a = (int*) malloc (sizeof(int));
if (a != NULL)
printf("Allocated memory for an integer\n");
else
printf("malloc() failed");
int x = 100;
//We can update the value to this location, since
//we have allocated memory for the pointer
*a = x;
printf("a points to %d\n", *a);
int* b;
//Will give a segmentation fault, since
//*b is not allocated any memory
*b = x;
printf("b points to %d\n", *b);
//Free memory from the heap
free(a);
return 0;
}
这个例子使用malloc()为a指向的整数位置分配内存。
由于已经分配了内存,因此可以更新该值。
但是另一个未在任何地方分配内存的指针b无法更新其值,并且由于尝试访问NULL位置而出现分段错误。
输出
Allocated memory for an integer a points to 100 [1] 14671 segmentation fault (core dumped) ./a.out
calloc()的示例
calloc()函数的用法与此类似,但是由于它分配内存块,因此我们可以使用它为数组分配内存。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
//Allocating memory dynamically on the heap
//for a character array of 50 characters and
//sets each element to zero.
char* a = (char*) calloc (50, sizeof(char));
if (a != NULL)
printf("Allocated memory for a character array\n");
else
printf("calloc() failed");
//We can use strcpy to copy to this array, since
//we have allocated memory
strcpy(a, "Hello from theitroad");
printf("The character array is:%s\n", a);
//Free the allocated memory
free(a);
return 0;
}
输出
Allocated memory for a character array The character array is:Hello from theitroad Freed memory from the heap

