We use malloc() and calloc() to dynamically allocate memory on the heap.

我们使用malloc()calloc()在堆上动态分配内存。

For a program, static memory allocation is done on its stack, where a predefined amount of memory is reserved for a particular variable.

对于程序,静态内存分配是在其堆栈上完成的,其中为特定变量保留了预定义的内存量。

In case the size of variable changes dynamically, we need to ensure that we can dynamically manage its memory. This is where malloc() and calloc() can be used, along with the realloc() and free() functions.

如果变量的大小动态变化,我们需要确保可以动态管理其内存。 在这里可以使用malloc()calloc()以及realloc()free()函数。

Let’s understand how we can use these functions to manage the heap.

让我们了解如何使用这些功能来管理堆。



malloc()和calloc()的语法 (Syntax for malloc() and calloc())

malloc() is used to allocate a user-defined number of bytes on the heap.

malloc()用于在堆上分配用户定义的字节数。

Since we associate memory locations with pointers, this also returns a pointer to that memory location.

由于我们将内存位置与指针相关联,因此这还将返回指向该内存位置的指针。


void* malloc(size_t size);

After we return the pointer, this will have allocated size bytes on the heap.

返回指针后,将在堆上分配size字节。

calloc() is similar, but it not only allocates memory but sets them to zero.

calloc()与之类似,但它不仅分配内存,而且将它们设置为零。


void* calloc(int num_blocks, size_t block_size);

This allocates num_blocks for the pointer, having a block size each, and sets the blocks to zero.

这为指针分配num_blocks ,每个都有一个block size ,并将块设置为零。

If the memory allocation fails for some reason, both malloc() and calloc() will return a NULL pointer.

如果由于某种原因内存分配失败,则malloc()calloc()都将返回NULL指针。

We can typecast the void* pointer to a pointer of our choice, like int, float, etc.

我们可以将void*指针类型转换为我们选择的指针,例如intfloat等。

NOTE: This is a part of the C standard library. So we must include the header file <stdlib.h>.

注意 :这是C标准库的一部分。 因此,我们必须包含头文件<stdlib.h>

Now that we’ve seen the syntax, let’s understand them a bit more clearly using some examples.

现在,我们已经了解了语法,下面通过一些示例让我们更加清楚地了解它们。



malloc()的示例 (Example for malloc())

Let’s look at an example for the malloc() function first.

首先让我们看一下malloc()函数的示例。


#include <stdio.h>
#include <stdlib.h>int main() {// Allocating memory dynamically on the heap// for an integer, which returns an int* pointerint* a = (int*) malloc (sizeof(int));if (a != NULL)printf("Allocated memory for an integer\n");elseprintf("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 heapfree(a);return 0;
}

This example uses malloc() to allocate memory for an integer location pointed by a. Since we have allocated memory, we can update the value. But another pointer b, which is not allocated memory anywhere, cannot update its value, and we get a segmentation fault since we try to access a NULL location.

本示例使用malloc()a指向的整数位置分配内存。 由于已经分配了内存,因此可以更新该值。 但是另一个未在任何地方分配内存的指针b无法更新其值,并且由于尝试访问NULL位置而出现分段错误。

Output

输出量


Allocated memory for an integer
a points to 100
[1]    14671 segmentation fault (core dumped)  ./a.out


calloc()的示例 (Example for calloc())

The calloc() function has a similar usage, but since it allocates blocks of memory, we can use it to allocate memory for arrays.

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");elseprintf("calloc() failed");// We can use strcpy to copy to this array, since// we have allocated memorystrcpy(a, "Hello from JournalDev");printf("The character array is:%s\n", a);// Free the allocated memoryfree(a);return 0;
}

Output

输出量


Allocated memory for a character array
The character array is:Hello from JournalDev
Freed memory from the heap


参考资料 (References)

  • Linux manual page for malloc()Linux手册页中的malloc()
  • Linux manual page for calloc()Linux手册页 calloc()
  • Related article: realloc() in C相关文章: C语言中的realloc()


翻译自: https://www.journaldev.com/35650/malloc-and-calloc-in-c

C中的malloc()和calloc()相关推荐

  1. calloc和malloc_malloc()vs calloc()– C中的malloc()和calloc()之间的区别

    calloc和malloc Here in this tutorial you will learn about difference between malloc() and calloc() in ...

  2. Linux中free函数头文件,Linux C 堆内存管理函数malloc()、calloc()、realloc()、free()详解...

    C 编程中,经常需要操作的内存可分为下面几个类别: 堆栈区(stack):由编译器自动分配与释放,存放函数的参数值,局部变量,临时变量等等,它们获取的方式都是由编译器自动执行的 堆区(heap):一般 ...

  3. malloc()与calloc区别【转】

    转自:http://blog.csdn.net/firecityplans/article/details/4490124/ 版权声明:本文为博主原创文章,未经博主允许不得转载. Both the m ...

  4. 【C/C++】内存分配函数:malloc,calloc,realloc,_alloca

    [C/C++]内存分配函数:malloc,calloc,realloc,_alloca malloc: 原型:extern void *malloc(unsigned int num_bytes); ...

  5. malloc 和 calloc的区别?

    函数malloc()和calloc()都可以用来动态分配内存空间,但两者稍有区别.malloc()函数有一个参数,即要分配的内存空间的大小:void *malloc(size_t size);call ...

  6. malloc与calloc的区别

    malloc()与calloc() C语言跟内存分配方式     1) 从静态存储区域分配.内存在程序编译的时候就已经分配好,这块内存在程序的整个运行期间都存在.例如全局变量,static变量.   ...

  7. 【校招面试 之 C/C++】第17题 C 中的malloc相关

    1.malloc (1)原型:extern void *malloc(unsigned int num_bytes); 头文件:#include <malloc.h> 或 #include ...

  8. malloc、calloc、realloc和free

    C 语言中开辟动态内存的有三个函数,分别为 malloc,calloc,realloc,释放内存的只有一个函数 free. realloc的使用是最容易犯错的,在写这篇博客前老师让我把realloc的 ...

  9. c语言malloc calloc,C语言内存管理:malloc、calloc、free的实现

    任何一个对C稍稍有了解的人都知道malloc.calloc.free.前面两个是用户态在堆上分配一段连续(虚拟地址)的内存空间,然后可以通过free释放,但是,同时也会有很多人对其背后的实现机制不了解 ...

最新文章

  1. BERT新转变:面向视觉基础进行预训练
  2. linux之SQL语句简明教程---IN
  3. python算法特征_python 3.x实现特征选择ReliefF算法
  4. 深度学习必备:随机梯度下降(SGD)优化算法及可视化
  5. sql多变量 双引号设置
  6. 特征对齐的旋转目标检测:Align Deep Features for Oriented Object Detection
  7. linux的系统移植——【PC-开发板】的环境搭建
  8. 非暴力拆解:小熊派NB-IoT通信扩展板
  9. JQuery和JavaScript常用方法的一些区别
  10. AcWing提高算法课Level-3 第四章 高级数据结构
  11. 正则表达式在python中的应用_详解Python中的正则表达式的用法
  12. linux下c语言 读取文件
  13. Java语言的Hook实现
  14. C盘满了怎么办?最强清理工具来了
  15. cramer定理_克莱姆(cramer)法则及定理简介.ppt
  16. 人脸识别数据集建立及应用
  17. 开优步认识各色各样的人,人生需要这样的新鲜体验!
  18. IT毕业生给学弟学妹们的真心话——离校座谈记录
  19. ios 故事板跳转
  20. 神策数据:数字化营销助力鞋服企业转型

热门文章

  1. pmm 监控mysql、mongodb、系统
  2. 唱吧DevOps的落地,微服务CI/CD的范本技术解读
  3. php单字母函数(快捷方法)使用总结转载
  4. 【转】Android 中的 Service 全面总结
  5. 网上邻居不能正常访问的处理
  6. 易学易用的Windows PowerShell(转)
  7. [转载] python输入一个年份、输出是否为闰年_Python程序检查给定年份是否为闰年
  8. [转载] Python函数中把列表(list)当参数
  9. [转载] python 常用类库!
  10. 从零开始——基于角色的权限管理01(补充)