Dynamic Memory Allocation
Dynamic Memory Allocation
Abdul Ghafoor
Faculty Member
Contents
• Memory Allocation
• Dynamic Memory Allocation
• Byte Manipulation functions
• Byte Ordering functions
Memory Allocation
• When a program is loaded into memory, it is
organized into three areas of memory, called
segments:
– text segment: where the compiled code of the
program itself resides.
heap
stack
<stdlib.h>
DMA Functions: malloc()
• The malloc() allocates un-initialized memory.
void *malloc(size_t requestedSize);
T *p;
p = (T *)malloc(sizeof(T));
int *q;
if((q = (int *) malloc(3*sizeof(int))) == NULL)
exit(1);
*q = 5;
DMA: calloc()
void *calloc(size_t nmemb, size_t size)
T *p;
p = (T *)calloc(10,sizeof(T));
int *q;
if((q = (int *)calloc(3, sizeof(int))) == NULL)
exit(1);
*q = 5;
DMA: realloc()
Example
• Example:
int *q;
if((q = (int *)calloc(3, sizeof(int))) == NULL)
exit(1);
*q = 5;
free(q);
DMA: alloca()
• The alloca() also allocates memory just like malloc
but memory is allocated on the stack rather than
heap.
MSB LSB
High-byte order Low-byte order big-endian byte order
A A+1
The same discussion applies to a 32 bit integer
Machines and Byte order
PowerPC-AIX Big-Endian
DEC-OSf4 Little-Endian
SUN-Solaris Big-Endian
HP-HPUX Big-Endian
586-Linux Little-Endian
Example
Byte Order
• Some systems use big-endian notation and some
systems use little-endian notation.