Passing An Array To A Function
Passing An Array To A Function
• Note: implementation of memory is left to the designers who design the syste
• Stack and heap can share the same pool of memory
• So the above diagram is only conceptual
Understanding dynamic Memory
Allocation
• program memory:
• Consists of the memory used for main and all called functions
• data memory:
• Consists of permanent definitions such as global data and
constants, local definitions and dynamic data memory
• Note: Exact ways of handling these needs will be decided by the OS and compiler
Understanding dynamic Memory
Allocation
• program memory:
• Consists of the memory used for main and all called functions
• main() must be in memory all the time
• Each called function must be in memory while it is active
//dynamic memory
int* x; //dynamic memory
x = malloc (. . . ); int* ary;
ary = calloc (. . . );
Figure 10-14 Memory Management Functions
//pInt = malloc(4);
malloc
• Successful call
• malloc returns the address of the first byte in the memory
allocated
• Unsuccessful call
• malloc returns a NULL pointer
• Overflow – attempt to allocate memory from the heap when
memory is insufficient
• Note: Refer to the memory allocated in the heap only through a pointer
• It does not have its identifier
calloc (contiguous memory allocation)
• Ex1: to release a single element allocated with a malloc back to the heap
• Ex2: : to release a 200 element array allocated with a calloc, all 200 elements are
returned back to the heap
free (releasing memory)
• It is not the pointers that are being released but what they
point to
• To release an array of memory that was allocated by calloc,
release the pointer only once
– Releasing memory does not change the value in a pointer
– It still contains the address in the heap
– It is a logical error to use the memory once it is released
– After freeing the memory, clear the pointer by setting to
NULL (to ease debugging)
free (releasing memory)