tomss
tomss

Reputation: 5

Malloc in C why to use it

I am new at C language and I need to create a queue and I don´t if I need to use a malloc (memory allocation) and how to use it. I had run add, remove, size and isempty without malloc and it worked.

    void e1_init(e1queue_t* q){
    q->head = 0;
    q->tail = sizeof(q->queue)/sizeof(int)-1;
    q->size=0;  
    }

Thanks.

Upvotes: 0

Views: 173

Answers (3)

Aniket Inge
Aniket Inge

Reputation: 25695

There are many reasons to use malloc() function.

  1. malloc() is used to dynamically allocate memory for variables. why? There can be many reasons to allocate memory dynamically. For instance if the size of a certain object/variable isn't known at COMPILE time, and there might be a reason to increase it later on, then its required to increase the memory requirement. and this is where malloc comes in.

  2. malloc() is used to initialize POINTERS why? POINTERS that aren't initialized point to a random location. This location may be in-accessible and might crash the program. When malloc is used, it increases the heap storage and points the randomly initialized pointer to a "sane" location, which can be read/written to.

  3. also, pointers initialized with malloc can be resized using realloc() method. This makes memory management flexible(and error prone as well)

Upvotes: 0

Jeremy J Starcher
Jeremy J Starcher

Reputation: 23863

In C, there are two kinds of memory:

  • The Stack
  • The Heap

Stack memory is rather limited and is used for automatic variables in functions, processing overhead, things like that.

When you need a larger chunk of memory, you need to get it from the heap.

Not an exact duplicate of this answer, but this seems to be a good description:

What and where are the stack and heap?

Upvotes: 1

NullPoiиteя
NullPoiиteя

Reputation: 57322

C dynamic memory allocation refers to performing dynamic memory allocation in the C programming language via a group of functions in the C standard library, namely malloc, realloc, calloc and free

Syntax:

#include <stdlib.h> 

Description:

The function malloc() returns a pointer to a chunk of memory of size size, or NULL if there is an error. The memory pointed to will be on the heap, not the stack, so make sure to free it when you are done with it.

Example:

typedef struct data_type {
  int age;
  char name[20];
} data;

data *bob;
bob = (data*) malloc( sizeof(data) );
if( bob != NULL ) {
  bob->age = 22;
  strcpy( bob->name, "Robert" );
  printf( "%s is %d years old\n", bob->name, bob->age );
}
free( bob ); 

Good Read C dynamic memory allocation

Upvotes: 0

Related Questions