2. Disclaimer: This presentation is prepared by trainees of
baabtra as a part of mentoring program. This is not official
document of baabtra –Mentoring Partner
Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .
Ltd
4. Functions with heap and
stack
Yasir musthafa pp
yasirmusthafapp@gmail.com
www.facebook.com/yasirmu
sthafa pp
twitter.com/yasirmusthafa
pp
in.linkedin.com/in/yasirmus
thafapp
8891396749
5. Stack
• special region of our computer's memory that
stores temporary variables created by each
function (including the main() function)
• "FILO" (first in, last out) data structure-
managed by CPU
• Every time a function declares a new variable-
pushed &popped
6. Stack (conti)
• variables are allocated and freed
automatically
• stack has size limits
• stack variables are local in nature
• stack variables is very fast
• variables cannot be resized
7. Example
#include <stdio.h>
double multiplyByTwo (double input) {
double twice = input * 2.0;
return twice;
}
int main (int argc, char *argv[])
{
int age = 30;
double salary = 12345.67;
printf("double your salary is %.3fn", multiplyByTwo(salary));
return 0;
}
output
double your salary is 24691.340
8. Heap
• region of our computer's memory that is not
managed automatically
• To allocate memory - malloc() or calloc()
• To delete memory – free()
• Memory leak
9. Heap(conti)
• variables can be accessed globally
• no limit on memory size
• (relatively) slower access
• you must manage memory (you're in charge
of allocating and freeing variables)
• variables can be resized using realloc()
10. Example
#include <stdio.h>
#include <stdlib.h>
double *multiplyByTwo (double *input) {
double *twice = malloc(sizeof(double));
*twice = *input * 2.0;
return twice;
}
int main (int argc, char *argv[])
{
int *age = malloc(sizeof(int));
*age = 30;
double *salary = malloc(sizeof(double));
*salary = 12345.67;
double *twiceSalary = multiplyByTwo(salary);
printf("double your salary is %.3fn", *twiceSalary);
free(age);
free(salary);
free(twiceSalary);
return 0;
}
11. When to use the Heap?
• you are dealing with relatively small variables
–stack
• you need to allocate a large block of memory
- heap
12. If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
13. Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com
IKK Road,
East Hill, Kozhikode
Kerala, India.
Ph: + 91 – 495 30 63 624
NIT-TBI,
NIT Campus, Kozhikode,
Kerala, India.