C中的malloc()和calloc()

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* 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;
}

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");
    else
        printf("calloc() failed");

    // We can use strcpy to copy to this array, since
    // we have allocated memory
    strcpy(a, "Hello from JournalDev");

    printf("The character array is:%s\n", a);
    
    // Free the allocated memory
    free(a);

    return 0;
}

Output

输出量


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


参考资料 (References)



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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值