Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and why to use malloc?

Well, I can't understand when and why it is needed to allocate memory using 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;?

like image 318
pr1m3x Avatar asked Jan 10 '12 08:01

pr1m3x


People also ask

Why would I use malloc?

Malloc is used for dynamic memory allocation and is useful when you don't know the amount of memory needed during compile time. Allocating memory allows objects to exist beyond the scope of the current block. C passes by value instead of reference.

Is it better to use malloc () or calloc ()?

Malloc() VS Calloc(): Explore the Difference between malloc() and calloc() malloc() and calloc() functions are used for dynamic memory allocation in the C programming language. The main difference between the malloc() and calloc() is that calloc() always requires two arguments and malloc() requires only one.

What is the point of using malloc in C?

Memory allocation (malloc), is an in-built function in C. This function is used to assign a specified amount of memory for an array to be created. It also returns a pointer to the space allocated in memory using this function.

Why do we use malloc instead of calloc?

Use malloc() if you are going to set everything that you use in the allocated space. Use calloc() if you're going to leave parts of the data uninitialized - and it would be beneficial to have the unset parts zeroed. 3.


1 Answers

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.

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.

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).

like image 82
taskinoor Avatar answered Sep 18 '22 01:09

taskinoor