何时以及为何使用malloc?

时间:2022-05-09 20:52:27

Well, I can't understand when and why it is needed to allocate memory using malloc.

我不明白为什么需要使用malloc分配内存。

Here is my code :

这是我的代码:

#include <stdlib.h>

int main(int argc, const char *argv[]) {

  typedef struct {
    char *name;
    char *sex;
    int age;
  } student;


  //Now I can do two things
  student p;

  //or
  student *ptr = (student *)malloc(sizeof(student));

  return 0;
}

Why is it needed to allocate memory when I can just use student p;?

当我只使用学生p时,为什么需要分配内存?

5 个解决方案

#1


31  

malloc is used for dynamic memory allocation. As said, it is dynamic allocation which means you allocate the memory at run time. For example when you don't know the amount of memory during compile time.

malloc用于动态内存分配。如前所述,它是动态分配,这意味着您在运行时分配内存。例如,当您不知道编译期间的内存数量时。

One example should clear this. Say you know there will be maximum 20 students. So you can create an array with static 20 elements. Your array will be able to hold maximum 20 students. But what if you don't know the number of students? Say the first input is the number of students. It could be 10, 20, 50 or whatever else. Now you will take input n = the number of students at run time and allocate that much memory dynamically using malloc.

一个例子应该清楚这一点。假设你知道最多有20个学生。你可以创建一个包含静态20元素的数组。你的阵列将能容纳最多20个学生。但是如果你不知道学生的数量呢?第一个输入是学生的数量。它可以是10 20 50,或者别的什么。现在您将输入n =运行时的学生数量,并使用malloc动态分配那么多内存。

This is just one example. There are many situations like this where dynamic allocation is needed.

这只是一个例子。有很多情况需要动态分配。

Have a look at the man page malloc(3).

请看手册页malloc(3)。

#2


15  

You use malloc when you need to allocate objects that must exist beyond the lifetime of execution of the current block (where a copy-on-return would be expensive as well), or if you need to allocate memory greater than the size of that stack (ie: a 3mb local stack array is a bad idea).

你需要时使用malloc分配对象必须存在生命周期之外的执行当前的块(copy-on-return是昂贵的),或者如果您需要分配内存大于栈的大小(即:3 mb本地堆栈数组是一个坏主意)。

Before C99 introduced VLA's, you also needed it to perform allocation of a dynamically sized array, however, its is needed for creation of dynamic data structures like trees, lists & queues, which are used by many systems. there are probably many more reasons, these are just a few.

在C99引入VLA之前,您还需要它来执行动态大小的数组分配,但是,它需要用于创建动态数据结构(如树、列表和队列),这是许多系统所使用的。可能还有更多的原因,这些只是少数。

#3


10  

Expanding the structure of the example a little, consider this:

稍微扩展一下示例的结构,考虑如下:

#include <stdio.h>

int main(int argc, const char *argv[]) {

typedef struct {
 char* name;
 char* sex;
 char* insurace;
 int age;
 int yearInSchool;
 float tuitionDue;
}student;


//Now I can do two things
student p;

//or
student *p = (student *)malloc(sizeof(student));

return 0
}

C a is language that implicitly passes by value, rather than by reference. In this example, if we passed 'p' to a function to do some work on it, we would be creating a copy of the entire structure. This uses additional memory (the total of how much space that particular structure would require), is slower, and potentially does not scale well (more on this in a minute). However, by passing *p, we don't pass the entire structure. We only are passing an address in memory that refers to this structure. The amount of data passed is smaller (size of a pointer), therefore the operation is faster.

C a是通过值而不是引用来传递的语言。在本例中,如果我们将'p'传递给一个函数来做一些工作,我们将创建整个结构的副本。它使用额外的内存(特定结构需要的空间的总和),速度较慢,并且可能不能很好地扩展(稍后详细介绍)。但是,通过传递*p,我们不会传递整个结构。我们只是在内存中传递一个地址,这个地址是指这个结构。传递的数据量更小(指针的大小),因此操作更快。

Now, knowing this, imagine a program (like a student information system) which will have to create and manage a set of records in the thousands, or even tens of thousands. If you pass the whole structure by value, it will take longer to operate on a set of data, than it would just passing a pointer to each record.

现在,了解了这一点,想象一个程序(就像一个学生信息系统)将必须创建和管理数千甚至数万条记录。如果您按值传递整个结构,那么对一组数据进行操作将花费更长的时间,而不是仅仅向每个记录传递一个指针。

#4


1  

malloc = Memory ALLOCation.

malloc =内存分配。

If you been through other programming languages, you might have used the 'new' keyword.

如果您使用过其他编程语言,您可能已经使用了“new”关键字。

Malloc does exactly the same thing in C. It takes a parameter, what size of memory needs to be allocated and it returns a pointer variable that points to the first memory block of the

Malloc在c中也做了同样的事情。它接受一个参数,需要分配多少内存,并返回一个指向第一个内存块的指针变量

entire memory block, that you have created in the memory. Example -

整个内存块,你在内存中创建的。的例子,

int *p = malloc(sizeof(int)*10);

Now, *p will point to first block of the consequtive 20 integer block reserved on the memory.

现在,*p将指向内存中保留的20个整数块的第一个块。

You can traverse through each block using the ++ and -- operator. All the best.

您可以使用+和-操作符遍历每个块。愿一切都好!

#5


0  

In this example it seems quite useless indeed. But now imagine that you are using sockets or file IO and must read packets from variable length which you can only determent while running. Or when using sockets and each client connection need some storage on the server. You could make an static array but this gives you a client limit which will be determent while compiling.

在这个例子中,它看起来确实毫无用处。但是现在假设您正在使用套接字或文件IO,并且必须读取可变长度的包,您只能在运行时进行测试。或者在使用套接字时,每个客户端连接都需要在服务器上存储一些数据。您可以创建一个静态数组,但是这会给您一个客户端限制,这将在编译时受到限制。

#1


31  

malloc is used for dynamic memory allocation. As said, it is dynamic allocation which means you allocate the memory at run time. For example when you don't know the amount of memory during compile time.

malloc用于动态内存分配。如前所述,它是动态分配,这意味着您在运行时分配内存。例如,当您不知道编译期间的内存数量时。

One example should clear this. Say you know there will be maximum 20 students. So you can create an array with static 20 elements. Your array will be able to hold maximum 20 students. But what if you don't know the number of students? Say the first input is the number of students. It could be 10, 20, 50 or whatever else. Now you will take input n = the number of students at run time and allocate that much memory dynamically using malloc.

一个例子应该清楚这一点。假设你知道最多有20个学生。你可以创建一个包含静态20元素的数组。你的阵列将能容纳最多20个学生。但是如果你不知道学生的数量呢?第一个输入是学生的数量。它可以是10 20 50,或者别的什么。现在您将输入n =运行时的学生数量,并使用malloc动态分配那么多内存。

This is just one example. There are many situations like this where dynamic allocation is needed.

这只是一个例子。有很多情况需要动态分配。

Have a look at the man page malloc(3).

请看手册页malloc(3)。

#2


15  

You use malloc when you need to allocate objects that must exist beyond the lifetime of execution of the current block (where a copy-on-return would be expensive as well), or if you need to allocate memory greater than the size of that stack (ie: a 3mb local stack array is a bad idea).

你需要时使用malloc分配对象必须存在生命周期之外的执行当前的块(copy-on-return是昂贵的),或者如果您需要分配内存大于栈的大小(即:3 mb本地堆栈数组是一个坏主意)。

Before C99 introduced VLA's, you also needed it to perform allocation of a dynamically sized array, however, its is needed for creation of dynamic data structures like trees, lists & queues, which are used by many systems. there are probably many more reasons, these are just a few.

在C99引入VLA之前,您还需要它来执行动态大小的数组分配,但是,它需要用于创建动态数据结构(如树、列表和队列),这是许多系统所使用的。可能还有更多的原因,这些只是少数。

#3


10  

Expanding the structure of the example a little, consider this:

稍微扩展一下示例的结构,考虑如下:

#include <stdio.h>

int main(int argc, const char *argv[]) {

typedef struct {
 char* name;
 char* sex;
 char* insurace;
 int age;
 int yearInSchool;
 float tuitionDue;
}student;


//Now I can do two things
student p;

//or
student *p = (student *)malloc(sizeof(student));

return 0
}

C a is language that implicitly passes by value, rather than by reference. In this example, if we passed 'p' to a function to do some work on it, we would be creating a copy of the entire structure. This uses additional memory (the total of how much space that particular structure would require), is slower, and potentially does not scale well (more on this in a minute). However, by passing *p, we don't pass the entire structure. We only are passing an address in memory that refers to this structure. The amount of data passed is smaller (size of a pointer), therefore the operation is faster.

C a是通过值而不是引用来传递的语言。在本例中,如果我们将'p'传递给一个函数来做一些工作,我们将创建整个结构的副本。它使用额外的内存(特定结构需要的空间的总和),速度较慢,并且可能不能很好地扩展(稍后详细介绍)。但是,通过传递*p,我们不会传递整个结构。我们只是在内存中传递一个地址,这个地址是指这个结构。传递的数据量更小(指针的大小),因此操作更快。

Now, knowing this, imagine a program (like a student information system) which will have to create and manage a set of records in the thousands, or even tens of thousands. If you pass the whole structure by value, it will take longer to operate on a set of data, than it would just passing a pointer to each record.

现在,了解了这一点,想象一个程序(就像一个学生信息系统)将必须创建和管理数千甚至数万条记录。如果您按值传递整个结构,那么对一组数据进行操作将花费更长的时间,而不是仅仅向每个记录传递一个指针。

#4


1  

malloc = Memory ALLOCation.

malloc =内存分配。

If you been through other programming languages, you might have used the 'new' keyword.

如果您使用过其他编程语言,您可能已经使用了“new”关键字。

Malloc does exactly the same thing in C. It takes a parameter, what size of memory needs to be allocated and it returns a pointer variable that points to the first memory block of the

Malloc在c中也做了同样的事情。它接受一个参数,需要分配多少内存,并返回一个指向第一个内存块的指针变量

entire memory block, that you have created in the memory. Example -

整个内存块,你在内存中创建的。的例子,

int *p = malloc(sizeof(int)*10);

Now, *p will point to first block of the consequtive 20 integer block reserved on the memory.

现在,*p将指向内存中保留的20个整数块的第一个块。

You can traverse through each block using the ++ and -- operator. All the best.

您可以使用+和-操作符遍历每个块。愿一切都好!

#5


0  

In this example it seems quite useless indeed. But now imagine that you are using sockets or file IO and must read packets from variable length which you can only determent while running. Or when using sockets and each client connection need some storage on the server. You could make an static array but this gives you a client limit which will be determent while compiling.

在这个例子中,它看起来确实毫无用处。但是现在假设您正在使用套接字或文件IO,并且必须读取可变长度的包,您只能在运行时进行测试。或者在使用套接字时,每个客户端连接都需要在服务器上存储一些数据。您可以创建一个静态数组,但是这会给您一个客户端限制,这将在编译时受到限制。