View
358
Download
1
Embed Size (px)
Citation preview
Recall
• What are functions used for?• What happens when we declare a
varaible? Say int a;• What is the difference between array
and structure?• What is the output if i print *p, p, &p
?
Introduction to CMemory Management
Week 3- day 1
When does memory allocated in C?
• There are two ways in which memory can be allocated in C:
–by declaring variables–by explicitly requesting space from
C
• Each case above space is allocated at different sectors of RAM
Where does memory allocated in C?
–by declaring variables - Stack–by explicitly requesting space from
C - Heap
Stack
Stack
• Stack is the place where all the variables that are declared and initialized before runtime are stored.
• Stack follows Last in First Out order(LIFO)
• When the program finishes stack will release all the spaces allocated for variables.
Stack
12
32
322
34
main(){
Int a=10,b=20,c;c=sum(a,b);
}int sum(int a,int b){
int c;c=a+b;return c;
}
RAM
Main()
a=10
b=20
c =30
sum()
a =10
b=20
C=30
What if there is no enough stack space?
Stack
Main()
Aaa()
Bbb()
Ccc()
Ddd()
Eee()
Fff()Stack Over flow
Heap
Heap
• Heap is the area of memory used for dynamic memory allocation
• Programmer allocates memory manually at heap ; and hence variable on the heap must be destroyed manually. There is no automatic release as in stack
23 32
43
45289
How to allocate space in heap?
• C inbuilt functions–Malloc() Allocates the
specified number of bytes
–Calloc() Allocates the specified number of bytes
and initializes them to zero
–Realloc() Increases or decreases the size of the
specified block of memory. Reallocates it if needed
–Free() Releases the specified block of memory
back to the system
Malloc()
• malloc() stands for "memory allocation"
• The malloc() function dynamically allocates memory when required.
• This function allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error
Syntaxmalloc(size_in_bytes);
But we need a pointer to point to the allocated space in heap
Malloc()
• Int *p;• P=malloc(2);
HEAP
2 byte memory
Stack
1000
1000
All are same !
int *p;p=malloc(2); //allocates 2 bytes
of memory
p=malloc(sizeof(Int)); //sizeof() returns size of any data type
so here it will be mallloc(2)
p=(int *)malloc(2); //malloc always return void * pointer . So you may type cast it into any data type.
but it is unnecessary as the compiler does it for us
p=(int *) (sizeof(int)); //allocates 2 bytes of memory type
casted to the integer type pointer
#include <stdio.h>#include <stdlib.h>void main(){
int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*)malloc(n*sizeof(int)); //memory allocated using malloc if(ptr==NULL)
{ printf("Error! memory not allocated."); exit(0); }Printf(“Enter the elements of Array”);For(i=0;i<n;++i){
Scanf(“%d”,ptr+i);Sum+=*(ptr+i);
}Printf(“sum=%d”,sum);free(ptr); // allocated memory is released
}
HEAPStack
n=101000ptr=1000
calloc()
• Calloc() stands for "contiguous allocation”• Allocates multiple blocks of memory each
of same size and sets all bytes to zero
• Syntax
calloc(number_of_elements,size_in_bytes);
Again we need a pointer to point to the allocated space in heap
calloc()
• Int *p;• P=calloc(3,10);
HEAP
10 bytes size
Stack
10001000
10 bytes size
10 bytes size
1001
1010
#include <stdio.h>#include <stdlib.h>void main(){
int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc if(ptr==NULL)
{ printf("Error! memory not allocated."); exit(0); }Printf(“Enter the elements of Array”);For(i=0;i<n;++i){
Scanf(“%d”,ptr+i); // Scanf(“%d”,&ptr[i]);Sum+=*(ptr+i);
}Printf(“sum=%d”,sum);free(ptr); // allocated memory is released
}
Malloc() Vs Calloc()
• Allocates "size" bytes of memory.
• The contents of allocated memory are not changed. i.e., the memory may contains garbage values.
• returns void pointer (void *). If the allocation succeeds, a pointer to the block of memory is returned.
• Allocates a region of memory large enough to hold "n elements" of "size" bytes each.
• The allocated region is initialized to zero.
• returns void pointer (void *). If the allocation succeeds, a pointer to the block of memory is returned.
Structure of Ram
Structure of Ram
TEXTAlso known as the code segment, holds the executable instructions of a program.• execute-only• fixed size
Structure of Ram
A global variable that is initialized and stored in the data segment.
This section has read/write attributes but cannot be shared among processes running the
same program.
Structure of Ram
This section holds uninitialized data. This data consists of global
variables that the system initializes with 0s upon program
execution. Another name for this section is the zero-initialized data
section.
Structure of Ram
When a program uses malloc() to obtain dynamic memory, this
memory is placed in the heap.
Structure of Ram
This contains all the local variables that get allocated. When
a function is called, the local variables for that function are
pushed onto the stack.
Questions?“A good question deserve a
good grade…”
Self Check !!
Self Check
• When the program execution ends variables in heap will be automatically released
–True–False
Self Check
• When the program execution ends variables in heap will be automatically released
–True–False
Self Check
• Reference to the heap memory will be stored in
•Heap•Stack•Gvar•BSS
Self Check
• Reference to the heap memory will be stored in
•Heap•Stack•Gvar•BSS
Self Check
• Difference between malloc() and calloc()
•Number of arguments•No of blocks• Initialization•All of above•None of above
Self Check
• Difference between malloc() and calloc()
•Number of arguments•No of blocks• Initialization•All of above•None of above
Self Check
• Complete the belowMain(){
int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*) malloc (n*sizeof(int));
}
Self Check
• Complete the belowMain(){
int n,i,*ptr,sum=0; printf("Enter number of elements: "); scanf("%d",&n); ptr=(int*) malloc (n*sizeof(int));
}
Self Check
Free()
Malloc()
Heap
Callloc()
Stack
Variables
2 arguments
Automatically free the memory
Automatically allocated in stack
Reserves one block of memory
Should be used when memory is dynamically allocated
Reference in stack
Self Check
Free()
Malloc()
Heap
Callloc()
Stack
Variables
2 arguments
Automatically free the memory
Automatically allocated in stack
Reserves one block of memory
Should be used when memory is dynamically allocated
Reference in stack
main(){
int i,a[10];for(i=0;i<10;i++){
printf(“Enter the number”);
scanf(“%d”,&a[i]);}
}
main(){
int i,*p,n;printf(“Enter the number of elements”);scanf(“%d”,&n);*p=calloc(n,sizeof(int));for(i=0;i<10;i++){
printf(“Enter the number”);
scanf(“%d”,&p [i]);}free(p);
}
Self Check
main(){
int i,a[10];for(i=0;i<10;i++){
printf(“Enter the number”);
scanf(“%d”,&a[i]);}
}
main(){
int i,*p,n;printf(“Enter the number of elements”);scanf(“%d”,&n);*p=calloc(n,sizeof(int));for(i=0;i<10;i++){
printf(“Enter the number”);
scanf(“%d”,&p [i]);}free(p);
}
Self Check
End of Day 1