language C - malloc, free, calloc

JameliaJamelia
2 min read

Let's first explain dynamic memory allocation all time in general use variables, and arrays are fixed size but what's you should do if you don't know the size of the array? have declared it? but if depends on another variable? that's the reason to use malloc, free,calloc.

some resources help you understand variables

https://en.wikipedia.org/wiki/C_data_types

malloc

the function is used to allocate a certain amount of memory during the execution of a program. It will request a block of memory from the heap. If the request is granted, the operating system will reserve the requested amount of memory and malloc will return a pointer to the reserved space.

When the amount of memory is not needed anymore, you must return it to the operating system by calling the function free.

calloc

it is very much similar to malloc() but has 2 different points and these are:

a- It initializes each block with a default value of ‘0’.

b- It has two parameters or arguments as compared to malloc().

free

after the allocated memory is doesn't need anymore, should return it to the operating system by returning the free function.

note: The free() function frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), malloc (), and realloc().

example on malloc and free represent how does write? and program doing?

reminder: sometimes, malloc fails. On error, malloc returns NULL. Always check its return value is NULL(capital letters)

at the end the secret sentence for malloc (allocated in memory value) and for free (doesn't needs anymore is returning to system operation by free ).

extra recourses to increase your knowledge

dynamics array: https://en.wikipedia.org/wiki/Dynamic_array

automatic variables: https://en.wikipedia.org/wiki/Automatic_variable

0
Subscribe to my newsletter

Read articles from Jamelia directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Jamelia
Jamelia

I am a developer from Earth plant, I am passionate about coding, and learning the frontend, C, C++